【问题标题】:Getting error Cannot read property 'setState' of undefined出现错误无法读取未定义的属性“setState”
【发布时间】:2017-09-28 18:46:02
【问题描述】:

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

【问题讨论】:

  • 您只需要将handleChange 绑定到组件。在构造函数中添加this.handleChange = this.handleChange.bind(this)

标签: reactjs react-redux


【解决方案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')
);
<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>

【讨论】:

  • 太好了,谢谢你们!您能否解释一下 this.handleChange = this.handleChange.bind(this) 与箭头函数之间的区别以及最佳实践是什么?谢谢
猜你喜欢
  • 1970-01-01
  • 2018-03-24
  • 1970-01-01
  • 1970-01-01
  • 2021-12-09
  • 1970-01-01
  • 2020-03-10
  • 2021-12-10
相关资源
最近更新 更多