当前位置: 移动技术网 > IT编程>网页制作>CSS > click处理函数提示报错(react事件处理)解决办法

click处理函数提示报错(react事件处理)解决办法

2018年08月04日  | 移动技术网IT编程  | 我要评论

绮罗卷,郑州手工活外发加工,台湾代理ip

运行以下click处理函数提示报错: Uncaught TypeError: Cannot read property ‘state’ of null

class Test extends React.Component {
  constructor(props) {
    super(props);
    this.state = { name: 'gt test' };
  }
   handleClick() {
    console.log(`Button is clicked  console ${ this.state.name }`);
  }
  render() {
    return (
      <button onClick={ this.handleClick }>
       click me
      </button>
    );
  }
};  

原因:这段代码中并没有保持同一个上下文,即处理函数没有同一个this; 

解决方法: 

1,<button onClick={ this.handleClick .bind(this) }>click me</button> 

但是react中button经常会被多次渲染,所以 bind 函数会一次又一次地被调用。 

2, 使用下面的方法:

constructor(props) {
  super(props);
  this.state = { name: 'gt test' };
  this.handleClick = this._handleButtonClick.bind(this);
}

3,<button onClick={ () => this.handleClick() }>click me</button> 

使用箭头函数执行也可以使处理函数和的上下文保持统一时。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网