class LoggingButton extends React.Component {
handleClick() {
console.log('this is:', this);
}
render() {
return (
<button onClick={this.handleClick}>
Click me
</button>
);
}
}
譬如:上面的这一段代码
如果没有留意绑定 this.handleClick 的话, 直接传给 onClick,就会招 Bug 的了。
因为当 handleClick 被调用的时候,里面的 this 会是 undefined
那么怎么才能保证 this 不会指代别的,而是我们想要的呢?有以下推荐方案
方案
使用 .bind(this) 使这个函数不论怎么调用都有同样的 this 值。将上面的例子代码改一改为:
<button onClick={this.handleClick.bind(this)}>
参考:bind()
其它的两种解决方案参考:文档