获取错误无法读取未定义的属性“setState”

时间:2017-05-01 10:27:36

标签: reactjs react-redux

我是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')
);

1 个答案:

答案 0 :(得分:1)

您应该绑定handleChange功能。您收到此错误是因为,在handleChange函数this中,keywork没有引用React类的上下文,因此您需要绑定该函数。

why do you need to bind event handlers in React

上查看此答案

&#13;
&#13;
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;
&#13;
&#13;