站内搜索:
首页 >> 前端 >> 内容
click处理函数提示报错(react事件处理)解决办法

时间:2018/7/11 15:23:17

运行以下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> 

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

  • 上一篇:前端实现网页自动跳转的三种方法介绍
  • 下一篇:vue自定义数字输入框组件代码实例讲解
  • 返回顶部