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

IT技术 javascript reactjs
2021-04-16 03:18:00

在新的 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 中需要绑定呢?

2个回答

您需要设置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()

您将函数与原始对象分离,现在函数调用发生在this内部tickFunc()引用全局对象的地方。

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

真正理解this和函数上下文的绝佳资源dmitripavlutin.com/gentle-explanation-of-this-in-javascript
2021-06-21 03:18:00