我是Reactjs的新手。我正在尝试做一个非常简单的事情:当用户在文本区域内更改文本时,在render函数中更新div。有什么建议?
class HTMLEditor extends React.Component { constructor(props) { super(props); this.state = {value: 'Put here HTML'}; } handleChange(e) { this.setState({value: e.currentTarget.value}); } render() { return ( <div> <textarea defaultValue={this.state.value} onChange={ this.handleChange } /> <div>{this.state.value}</div> </div> ); } } ReactDOM.render( <HTMLEditor />, document.getElementById('container') );
您应该绑定该handleChange函数。您收到此错误的原因是,在handleChange函数中,this键盘操作未引用React类的上下文,因此您需要绑定该函数。
handleChange
this
看到这个答案 why do you need to bind event handlers in React
why do you need to bind event handlers in React
class HTMLEditor extends React.Component { constructor(props) { super(props); this.state = {value: 'Put here HTML'}; } handleChange = (e) =>{ this.setState({value: e.currentTarget.value}); } render() { return ( <div> <textarea defaultValue={this.state.value} onChange={ this.handleChange } /> <div>{this.state.value}</div> </div> ); } } ReactDOM.render( <HTMLEditor />, document.getElementById('container') ); <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="container"></div>