dha*_*0us 2 javascript bind this reactjs
我试图捕获输入的onChange事件并使用新值调用setState,但是一旦输入输入,我得到:
Uncaught TypeError: Cannot read property 'setState' of undefined
Run Code Online (Sandbox Code Playgroud)
即使我打过电话
this.handleChange.bind(this)
Run Code Online (Sandbox Code Playgroud)
在构造函数中
index.js
import React from 'react'
import * as ReactDOM from "react-dom";
import App from './App'
ReactDOM.render(
<App />,
document.getElementById('root')
);
Run Code Online (Sandbox Code Playgroud)
App.js
import * as React from "react";
export default class App extends React.Component {
constructor(props) {
super(props)
this.handleChange.bind(this)
this.state = {contents: 'initialContent'}
}
handleChange(event) {
this.setState({contents: event.target.value})
}
render() {
return (
<div>
Contents = {this.state.contents}
<input type="text" onChange={this.handleChange}/>
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
Ale*_* T. 10
赋值this.handleChange.bind(this)(bind - 返回对函数的新引用)到this.handleChange.,因为this.handleChange必须引用返回的新函数.bind
constructor(props) {
super(props)
this.handleChange = this.handleChange.bind(this)
this.state = {contents: 'initialContent'}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1000 次 |
| 最近记录: |