javascript - React : When not bound, 'this' 为 null,而不是 React 组件事件处理程序中未定义

标签 javascript reactjs ecmascript-6

我正在查看有关处理事件的 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/

相关文章:

javascript - 条件对象属性的流类型问题

javascript - 如何使用 Javascript 变量作为 DOM

javascript - 如何生成与值成比例的CSS颜色?

reactjs - 将 API token 保存到本地存储 ReactJS

reactjs - Ant 设计输入组件不更新值

reactjs - Element.createShadowRoot 已弃用,并将于 2019 年 3 月左右在 M73 中删除。请改用 Element.attachShadow

使用 index.js 从 '/folder' 导入 javascript

javascript - Nodejs 无法使用 axios 在 get 请求中发送 oauth v1 参数

javascript - 如何使用 HOC 编写适当的 Jest 测试?

javascript - "Uncaught Cannot extend unknown button type: copyHtml5"- 如何使用 `datatables.net-buttons-bs4`