是否用ES6箭头反应onChange函数

时间:2018-09-19 19:30:24

标签: reactjs forms ecmascript-6 javascript-events arrow-functions

在处理onChange事件时,该事件有效

<input type="file" onChange={this.onChange}

不是这个,它可以立即执行功能

<input type="file" onChange={this.onChange()}

没有其他人,不执行

<input type="file" onChange={() => this.onChange}

但是这个有

<input type="file" onChange={() => this.onChange()}

但是,虽然第一个自动发送 event 对象,但第二个需要显式显示

<input type="file" onChange={(e) => this.onChange(e)}
onChange(e) {
    console.log(e.target.files[0])
}

那是为什么?什么时候应该使用另一个?

2 个答案:

答案 0 :(得分:6)

<input type="file" onChange={this.onChange}

之所以可行,是因为onChange道具是一个函数,然后您将函数引用传递给它,因此它起作用了。 <input>负责将事件参数传递给它。


<input type="file" onChange={this.onChange()}

这不起作用,因为您要为onChange prop分配onChange函数的结果值。 (但是根据您的功能,它可能会起作用)


<input type="file" onChange={() => this.onChange}

这也行不通,因为您正在创建一个新函数,并且在其中使用的是对函数this.onChange的引用,而您没有执行它(带括号)。


<input type="file" onChange={() => this.onChange()}

这将在您的匿名函数中执行该函数(您正在调用this.onChange()),但是没有将参数传递给它,那么您如何期望在this.onChange函数中获取事件信息?


<input type="file" onChange={(e) => this.onChange(e)}
onChange(e) {
    console.log(e.target.files[0])
}

这解决了我先前的观点,现在在您的匿名函数中,您正在获取事件信息e,并将其传递给onChange函数。然后就可以了。

答案 1 :(得分:4)

使用onChange={(e) => this.onChange(e)},您实际上是在创建一个新函数,该函数在每个渲染期间调用 this.onChange 方法。

使用onChange={this.onChange},您可以直接访问 this.onChange 方法。此方法仅定义一次,并且可以多次使用。基本上,您避免使用新的渲染创建新功能,从而使应用程序的性能略有提高

相关问题