【问题标题】:react setstate TypeError: Cannot read property 'setState' of undefined [duplicate]反应setstate TypeError:无法读取未定义的属性'setState' [重复]
【发布时间】:2018-10-06 21:56:06
【问题描述】:
class CheckBox extends React.Component{
  constructor(checked){
    super(checked);
    this.state={checked:false}
  }
  handleChange(event){
    this.setState({checked:!this.state.checked});
  }
  render(){
    var msg;
    if(this.state.checked){
      msg= "checked"
    }else{
      msg="unchecked"
    }
    return(
      <div>
        <input type="checkbox" onChange={this.handleChange} />
        <h3>Checkbox is {msg}</h3>
      </div>
    );
  }
}

它说

TypeError: 无法读取未定义的属性“setState”

不知道原因

【问题讨论】:

  • 你必须绑定你的handleChange()函数。您可以在构造函数中执行此操作:this.handleChange = this.handleChange.bind(this);

标签: reactjs


【解决方案1】:

在构造函数中将this 绑定到您的函数

constructor(checked){
    super(checked);
    this.state={checked:false}

    this.handleChange = this.handleChange.bind(this);

}

https://jsfiddle.net/gaby/chazb1ju/


或者在将处理程序绑定到事件时传递箭头函数

<input type="checkbox" onChange={(e)=>this.handleChange(e)} />

https://jsfiddle.net/gaby/sjjrrtsu/

【讨论】:

  • 或者只是绑定handleChange(),使其成为箭头函数。
猜你喜欢
  • 2020-09-07
  • 2017-01-01
  • 2017-07-09
  • 2017-05-30
  • 2017-10-30
  • 1970-01-01
相关资源
最近更新 更多