绮罗卷,郑州手工活外发加工,台湾代理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>
使用箭头函数执行也可以使处理函数和的上下文保持统一时。
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
[书籍精读]《响应式Web设计 HTML5和CSS3实战(第二版)》精读笔记分享
网友评论