我将 ReactJS 与 Babel 和 Webpack 一起使用,并使用 ES6 以及 建议的箭头函数类字段。我知道箭头函数通过 不重新创建每个渲染的函数 来提高效率,类似于构造函数中的绑定工作方式。但是,我不能 100% 确定我是否正确使用了它们。以下是我在三个不同文件中的代码的简化部分。
我的代码:
主.js
prevItem = () => {
console.log("Div is clicked")
}
render(){
return (
<SecondClass prevItem={this.prevItem} />
)
}
SecondClass.js
<ThirdClass type="prev" onClick={()=>this.props.prevItem()} />
ThirdClass.js
<div onClick={()=>{this.props.onClick()}}>Previous</div>
问题:
我上面的代码是否正确使用了箭头功能?我注意到对于 SecondClass.js 我也可以使用:
<ThirdClass type="prev" onClick={this.props.prevItem} />
由于我在原始函数定义中使用了 ES6 箭头函数,因此一种方法或另一种方法之间有区别吗?或者我应该一直使用箭头语法直到最后一个 div 吗?
原文由 kojow7 发布,翻译遵循 CC BY-SA 4.0 许可协议
这不是真的。这取决于您使用箭头功能的确切位置。如果
Arrow function
在渲染方法中使用,那么它们将创建一个新实例everytime
渲染就像bind
一样被调用。考虑这个例子这里每次调用 render 都会创建一个匿名函数,调用该函数时调用
this.onClick
。但是考虑下面的情况
在上面的例子中,箭头函数并不是每次都重新创建函数,而是在实例化类时将上下文绑定到 React 组件,如
An arrow function does not have its own this; the this value of the enclosing execution context is used.
一次。这类似于binding works is constructor
的方式。这是proposed class fields for arrow functions
的一部分,它不是 ES6 功能,要理解您想问什么,您必须知道函数从调用它的地方获取上下文。检查
this question
以获得更多理解。在您的情况下,您使用了
Arrow function
来定义prevItem
因此它获得了封闭的 React 组件的上下文。Now in its child, even if you call
prevItem
with any custom context,using bind or arrow function
,prevItem
when executed in parent ieMain.js
will get其封闭的 React 组件的上下文。并且由于您只想执行 prevItem 函数并且不想将任何数据从孩子传递给它,所以写和
根本没用,只会增加性能影响,因为每次都会在
SecondClass
和ThirdClass
中创建新函数。您根本不需要将这些函数定义为箭头函数,只需编写和
因为它已经绑定在父级中。
现在,即使您必须从 ThirdClass 和 SecondClass 向这些函数传递一些额外的数据,您也不应直接使用
Arrow function
或bind in render
。看看这个答案How to Avoid binding in Render method