【问题标题】:React onChange functions with ES6 arrows or not是否使用 ES6 箭头响应 onChange 函数
【发布时间】:2019-02-24 01:13:04
【问题描述】:

在处理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])
}

这是为什么呢?我们什么时候应该使用其中一个?

【问题讨论】:

  • 尝试添加console.log(this),看看两种工作方式的区别
  • 我没提但是绑定了:this.onChange = this.onChange.bind(this)
  • 在这种情况下,额外的箭头函数包装是完全多余的,不应该使用。
  • 参见bindstackoverflow.com/questions/43600967/…。这适用于 React 的程度低于通用 OOP,但通常bind 更可取。

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


【解决方案1】:
<input type="file" onChange={this.onChange}

这是有效的,因为onChange prop 是一个函数,然后您将函数引用传递给它,所以它有效。而&lt;input&gt;负责将事件参数传递给它。


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

这不起作用,因为您将 onChange 函数的结果值分配给 onChange prop。 (但取决于你的功能,它可以工作)


<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 函数。然后就可以了。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 感谢您的两个回答 :) 这个对我来说比较清楚
    猜你喜欢
    • 2017-10-20
    • 2015-12-18
    • 2019-01-06
    • 1970-01-01
    • 2016-11-07
    • 2016-09-07
    • 2022-01-21
    • 2016-03-25
    相关资源
    最近更新 更多