**
react学习中关于事件绑定this的理解
官方原文"为了在回调中使用 this
,这个绑定是必不可少的"
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// 为了在回调中使用 `this`,这个绑定是必不可少的
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(state => ({
isToggleOn: !state.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
ReactDOM.render(
<Toggle />,
document.getElementById('root')
);
经过测试在构造方法中将事件绑定this的语句注释之后发现事件触发后报错,其中的this打印后显示为undefined,由于React使用的是ES6中的class,而使用 class 创建的对象,在没有通过new 去实例化的之前,它的内部方法this是无绑定状态的。所以此时需要在构造方法中手动给this.handleClick绑定this。
下图为JSX转为JS后的代码,render函数中this能获取到数据是因为经过编译后render函数中的this指向的是_createClass函数中的第一个参数,也就是Toggle对象,所以能够获取到this