在 React 中,为什么渲染方法绑定到组件实例而不是自定义方法?

In React why is the render method bound to component instance but not custom methods?

在 class 中,为什么 render 方法自动绑定到组件实例,但自定义方法,例如事件处理程序不是?

我知道使用 bind 关键字使这些事件处理程序工作,但只是想找到一个答案,为什么可以在 render 方法中引用“this”,但为什么它也不会自动绑定到事件处理程序方法中?

引用 React's docs:

You have to be careful about the meaning of this in JSX callbacks. In JavaScript, class methods are not bound by default. If you forget to bind this.handleClick and pass it to onClick, this will be undefined when the function is actually called.

虽然将它们定义为箭头函数,但仍在实例级别,会将范围更改为组件的实例。所以所有其他方法,如 rendercomponentDidMount 都是 class' 定义的一部分,而不是事件处理程序,这意味着 this 将指向其中的实例(通常JavaScript 此类方法的行为)。

最后,您始终可以使用 apply or call 调用具有不同作用域的方法,更改这些方法中 this 所指的内容。

why is the render method automatically bound to the component instance

未绑定。只是 React 总是使用正确的上下文调用渲染函数。

对于普通函数,this 的值取决于您调用函数的方式。在下面的代码中,example. 是说明 this 的值将在函数内部的部分。

const example = {
  value: 'abc',
  printValue: function () {
    console.log(this.value);
  }
}

example.printValue(); // abc

但是如果你以不同的方式调用函数,你可以获得不同的值this

const example = {
  value: 'abc',
  printValue: function () {
    console.log(this.value);
  }
}

const temp = example.printValue;

console.log(temp === example.printValue); // true (they're literally the same function)
temp(); // undefined, or throw an exception depending on if we're in strict mode

所以每次 react 调用 render 函数时,它都会以第一种方式(或类似的方式)调用它,而不是第二种方式。