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

问题描述

在一个类中,为什么 render 方法会自动绑定到组件实例,而自定义方法(例如事件处理程序)却没有?

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

标签: javascriptreactjsclassscopeevent-handling

解决方案


为什么render方法会自动绑定到组件实例

它不受约束。只是 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 调用渲染函数时,它都会以第一种方式(或与之等效的方式)调用它,而不是第二种方式。


推荐阅读