【发布时间】:2017-10-25 17:49:01
【问题描述】:
我正在浏览 https://facebook.github.io/react/docs/handling-events.html 处理事件的反应文档
有这部分提到了下面这行:“在JavaScript中,类方法默认是不绑定的。如果你忘记绑定this.handleClick并将它传递给onClick,那么在实际调用该函数时this将是未定义的。”
Codepen 上提供了一个示例。我尝试通过注释掉绑定 "this.handleClick = this.handleClick.bind(this);" 并在 handleClick 方法上添加“console.log(this)”。 这是编辑后的分叉版本: http://codepen.io/anakornk/pen/wdOqPO
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// This binding is necessary to make `this` work in the callback
// this.handleClick = this.handleClick.bind(this);
}
handleClick() {
console.log(this);
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
ReactDOM.render(
<Toggle />,
document.getElementById('root')
);
根据上面文档中的说法,输出应该是"undefined",但是显示的是"null"。
这是为什么?
【问题讨论】:
-
我相信这是基于 React 如何在内部处理子类和组件的差异。没有 React 而只有 ES6,当你不调用带有上下文的方法时,它将是未定义的。
标签: javascript reactjs ecmascript-6