我是Reactjs的新手。我正在尝试做一些非常简单的事情:当用户更改文本区域内的文本时,更新渲染函数中的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')
);
答案 0 :(得分:1)
您应该绑定handleChange
功能。您收到此错误是因为,在handleChange函数this
中,keywork没有引用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')
);
&#13;
<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>
&#13;