这两种声明在react javascript中的区别是什么?
What is the difference between these two declarations in react javascript?
我使用类语法来声明一个react组件:
import React, {Component} from 'react'
class Page extends Component {
constructor(props) {
super(props)
this.state = {value: ''}
}
doA(event) {this.setState({value: event.target.value})}
doB = (event) => {this.setState({value: event.target.value})}
render {
return (
<input type="text" onChange={this.doB}/>
{*the following is wrong:*}
{*<input type="text" onChange={this.doA}/>*}
)
}
}
如果我尝试使用doA
处理onChange
,我得到这个错误:TypeError: Cannot read property 'setState' of undefined
.
doA
的声明看起来更像是Java中的一个类方法,而doB
的声明看起来更像是一个分配给类属性的匿名函数。我本以为使用onChange = this.doA
会保持this
分配给类,但它是反过来的。onChange = doB
保持this
赋值给类。
我试着搜索解释,但我不知道适当的术语,因此我的搜索条件很差。
旁注:如果我使用onChange = doA
,我得到那个错误,但输入字段仍然会正确更新。所以this.state.value
在变化,但它给了我那个错误。为什么呢?
JavaScript中的箭头函数以词法绑定this
。这就是doB
正常工作而doA
不工作的原因。
如果您将doA
绑定到constructor
中,使用类语法将像预期的那样工作:
constructor(props) {
super(props);
this.doA = this.doA.bind(this);
}
相关文章:
- 这是什么 ==- javascript 运算符
- 我的单元测试选项是什么
- 打破承诺链的好方法是什么
- 在AngularJS应用程序中使用封装指令和路由的推荐方式是什么
- Javascript中的空白是什么
- 是什么让一个“;Uncaught RangeError:超过了最大调用堆栈大小“;错误(Chrome,在其他浏览器中显示
- 在JavaScript中拆分日期字符串的更好方法是什么
- 将jQuery.ech()方法转换为本地JavaScript抽象的最佳方法是什么
- 处理浮点错误的最佳方法是什么
- javascript导入的最佳实践是什么
- 基于窗口宽度jquery的函数的替代方法是什么
- 在ng重复循环中显示条件内容的最佳方式是什么
- 我的客户端选项是什么
- 这是什么“;要求“;事情
- 未捕获的类型错误:topFrame.window.changeSelectedBarStyle不是函数,原因是什么
- 实现比较方法的最佳实践是什么;s的比较类型是在运行时选择的
- @@(“at at”)在ES6 JavaScript中是什么意思
- knex:根据结果创建数组的合适方法是什么
- emu -model、emu -restless和emu之间的主要区别(优缺点)是什么?
- function()在jQuery中是什么意思?这个和$(这个)有什么区别