javascript - 在 React 中,为什么渲染方法绑定到组件实例而不是自定义方法?
问题描述
在一个类中,为什么 render 方法会自动绑定到组件实例,而自定义方法(例如事件处理程序)却没有?
我理解使用 bind 关键字使这些事件处理程序工作,但只是试图找到一个答案,为什么可以在渲染方法中引用“this”,但为什么它也不会自动绑定在事件处理程序方法中?
解决方案
为什么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 调用渲染函数时,它都会以第一种方式(或与之等效的方式)调用它,而不是第二种方式。
推荐阅读
- javascript - Leaflet - 设置工具提示的样式
- java - 需要帮助将 DCGAN 转换为 Java 以用于 Java 的 Tensorflow
- xpath - Google 表格中特定网站的 XPath
- couchdb - 如何使用基于键返回精确值的数组键在 CouchDB 中查询
- javascript - 必须在自动完成建议上单击两次才能填充到文本字段
- python - 将变量从 python 文件传递到 JS 文件(节点)
- javascript - 加速操作系统驱动器遍历
- python - 对同情中的负数感到困惑
- matlab - 在 MATLAB 中创建一个元素数量有限的矩阵
- python - 程序是:使用循环从键盘获取 10 个整数并在屏幕上打印它们的平均值