为什么在ES6-react类中需要绑定

Why binding is needed in ES6 react classes

本文关键字:绑定 ES6-react 为什么      更新时间:2023-09-26

在新的React ES6类中,this需要绑定,如下所述: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将绑定

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中需要绑定?

您需要将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

ES6中的类是函数。当你实例化一个类时,你会得到一个对象。对于类中的所有方法,如果在其中使用this,则它引用拥有该方法的对象。

但是,由于上下文的变化,提取方法时会令人困惑。示例:

let foo = Counter()
foo.tick()

如果调用foo.tick(),则this属于对象foo。凉的

但请注意:

tickFunc = foo.tick()
tickFunc()

您将函数与原始对象分离,现在函数调用发生在tickFunc()中的this引用全局对象的位置。

那么,为什么你需要在React中绑定你的方法呢?之所以这样做,是因为大多数时候我们将方法引用传递给事件处理程序或作为组件的道具。当您传递方法的引用时,它们会变成分离的函数,并且它们的上下文会发生变化。要解决这个问题,可以在构造函数中使用bind()