我正在浏览https://facebook.github.io/react/docs/handling-events.html上有关处理事件的react文档

在该部分中提到了以下行:“在JavaScript中,默认情况下未绑定类方法。如果忘记绑定this.handleClick并将其传递给onClick,则在实际调用函数时将无法定义。”

在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”。

为什么是这样?

最佳答案

您可以在此行上设置断点并检查调用堆栈。

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)())

09-30 16:24
查看更多