【问题标题】:React: When not bound, 'this' is null instead of undefined in React component event handlerReact:当未绑定时,'this' 为 null 而不是在 React 组件事件处理程序中未定义
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2017-06-14
    • 2017-03-19
    • 2016-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-03
    • 2015-06-26
    相关资源
    最近更新 更多