运行以下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>
使用箭头函数执行也可以使处理函数和组件的上下文保持统一时。