我正在查看有关处理事件的 react 文档 https://facebook.github.io/react/docs/handling-events.html
其中有这样一句话:“在 JavaScript 中,类方法默认是不绑定(bind)的。如果你忘记绑定(bind) this.handleClick 并将其传递给 onClick,那么当函数实际调用时,this 将是未定义的”
Codepen 上提供了一个示例。我尝试通过注释掉绑定(bind)来删除 “this.handleClick = this.handleClick.bind(this);” 并在handleClick方法上添加“console.log(this)”。 这是编辑后的 fork 版本: 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”。
这是为什么?
最佳答案
您可以在此行设置断点并检查调用堆栈。
ReactErrorUtils.invokeGuardedCallback = function (name, func, a, b) {
var boundFunc = func.bind(null, a, b); // <-- this is why context is null
var evtType = 'react-' + name;
fakeNode.addEventListener(evtType, boundFunc, false);
var evt = document.createEvent('Event');
evt.initEvent(evtType, false, false);
fakeNode.dispatchEvent(evt);
fakeNode.removeEventListener(evtType, boundFunc, false);
};
"use strict"
function fn() {
return this;
}
console.log(fn(), fn.bind(null)())
关于javascript - React : When not bound, 'this' 为 null,而不是 React 组件事件处理程序中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44174379/