2016-08-18 115 views
0

我使用的是类的语法来声明一个反应成分:这两个声明在反应JavaScript之间有什么区别?

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}/>*} 
     ) 
    } 
} 

如果我尝试使用doAonChange来处理,我得到这个错误:TypeError: Cannot read property 'setState' of undefined

doA的声明看起来更像Java中的类方法,并且doB的声明看起来更像是分配给类属性的匿名函数。我本来以为onChange = this.doA会保留this分配给这个班级,但这是相反的。 onChange = doB保留this分配给该类。

我试着寻找解释,但我不知道正确的术语,因此我的搜索条件很差。

附注:如果我使用onChange = doA,则会出现该错误,但输入字段仍然会正确更新。所以this.state.value正在改变,但它给了我这个错误。这是为什么?

回答

1

JavaScript中的箭头函数在词汇上为您绑定this。这就是doB正常工作的原因,而doA没有。

如果您在constructor结合doA,如使用类语法预期的事情会:

constructor(props) { 
    super(props); 
    this.doA = this.doA.bind(this); 
}