这两种声明在react javascript中的区别是什么?

What is the difference between these two declarations in react javascript?

本文关键字:区别 是什么 javascript 两种 声明 react      更新时间:2023-09-26

我使用类语法来声明一个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);
}