我正在尝试捕获输入的 onChange 事件并使用新值调用 setState ,但是只要输入输入,我就会得到:
Uncaught TypeError: Cannot read property 'setState' of undefined
即使我已经打电话了
this.handleChange.bind(this)
在构造函数
中index.js
import React from 'react'
import * as ReactDOM from "react-dom";
import App from './App'
ReactDOM.render(
<App />,
document.getElementById('root')
);
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>
);
}
}
答案 0 :(得分:9)
将this.handleChange.bind(this)
( bind - 返回对函数的新引用)分配给this.handleChange
。,因为{{ 1}}必须引用返回this.handleChange
.bind