javascript - 为什么在 ES6 react 类中需要绑定(bind)

标签 javascript reactjs

在新的 React ES6 类中,this 需要按照此处所述进行绑定(bind):http://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding 例如:

class Counter extends React.Component {
  constructor() {
    super();
    this.tick = this.tick.bind(this);
  }
  tick() {
    ...
  }
  ...
}

对此的解释是因为它是默认行为,但是如果我创建一个 ES6 类,然后创建它的一个新实例,this 将被绑定(bind)

import React from 'React'

class Test extends React.Component {
    constructor() {
      super()
    }
    foo () {
      console.log('bar')
    }
    hello() {
      this.foo()
    }
}

var test = new Test()
test.hello()
// > bar

为什么 React 需要绑定(bind)?

最佳答案

您需要为方法设置 this 以防万一,例如,如果您需要将函数引用传递给事件处理程序,但是您不需要为每个方法都设置 this .,

class Counter extends React.Component {
  constructor() {
    super();
    this.tick = this.tick.bind(this);
  }

  tick() {
    // this refers to Counter
  }

  fn() {
    // this refers to Counter
  }

  withoutBind() {
    // this will be undefined or window it depends if you use "strict mode" or not
  }

  render() {

    this.fn(); // this inside this method refers to Counter

    // but if you will do like this
    const fn = this.fn;
    fn(); // this will refer to global scope


    return <div>
      <button onClick={this.tick}>1</button>
      <button onClick={this.withoutBind}>2</button>
    </div>;
  }
}

Example

关于javascript - 为什么在 ES6 react 类中需要绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36309636/

相关文章:

javascript - jquery ui 自动完成结果框在左上角

javascript - 我无法从 Javascript 触发自定义事件

reactjs - 部署到 GitHub 的 React 应用程序给我一个缩小的错误 #152

javascript - React如何拥有不受React路由器影响的组件

reactjs - 如何在 TestCafe 中单击未渲染的虚拟化元素

reactjs - componentWillUpdate 读取旧状态

javascript - 如何从 chrome 扩展 webRequest api 获取引荐来源网址?

javascript - 引导日期选择器 : how to close only when clicking outside

javascript - 在谷歌可视化数据表上调用ajax函数点击

reactjs - 为什么 Google AdSense 没有与 Reactjs 一起显示?