reactjs - 为什么我的类方法可以在 React 中工作而没有显式地将它绑定到“this”?
问题描述
我束手无策,有人能告诉我为什么这行得通,即使我注释掉了对“this”的显式绑定吗?据我了解,如果没有明确绑定到类,则“this”应该是未定义的,因此这个例子应该给我一个错误,但它确实有效。我错过了什么?
import React, { Component } from 'react';
class Counter extends Component {
constructor(props) {
super(props);
this.state = {
count: 1
};
// this.handleAdd = this.handleAdd.bind(this);
// this.handleAdd = this.handleSub.bind(this);
}
handleAdd() {
this.setState(prevState => ({ count: prevState.count + 1 }));
}
handleSub() {
this.setState(prevState => ({ count: prevState.count - 1 }));
}
render() {
return (
<div>
<h1>Counter is at {this.state.count}</h1>
<button onClick={() => this.handleAdd()}>+</button>
<button onClick={() => this.handleSub()}>-</button>
</div>
)
}
}
export default Counter;
解决方案
这是因为您正在使用箭头函数来调用您的方法。箭头函数this
绑定到最近的非箭头父函数中的值。
推荐阅读
- serialization - 将 DataFrame 保存到文件的 Julia 的序列化不适用于长文件名
- sql - 从Oracle SQL中具有日期数据类型的列中获取具有日期范围的记录作为过滤器
- reactjs - react native 有稳定版本吗(因为版本从零开始就问)
- flutter - 在 Dart 中将 double 和 integer 转换为货币
- c# - 如何从光标位置获取应用程序标题(标题)(winapi)
- type-conversion - 我正在尝试在 talend tmap 中将日期格式从 yyyy-mm-dd 更改为 dd-mm-yyyy 请帮助我?
- c++ - GCC 和 Clang 的简单浮点计算结果不一致
- java - 为什么 java 让我将 Box(Raw 类型) 添加到 List
> - python - 使用 CV2 和 Linux 设置 Logitech C920 自动对焦 - 相机忽略子进程设置的手动设置
- c# - 第一个异步方法是如何创建的?