Reactjs 什么时候应该将React类中的函数定义为arrow函数?
我正在使用React创建一个网页。有一个Reactjs 什么时候应该将React类中的函数定义为arrow函数?,reactjs,arrow-functions,Reactjs,Arrow Functions,我正在使用React创建一个网页。有一个text区域,我们可以在那里输入文本。因此,在return内部,onChange链接到名为inputChange的函数: <textarea value={this.state.text} onChange=...></textarea> 另一种方法是将其定义为箭头函数(称为类属性?): (我注意到的一点是,如果我们将inputChange定义为箭头函数,我们可以将inputChange视为this的一个属性,当我们在内部打印th
text区域
,我们可以在那里输入文本。因此,在return
内部,onChange
链接到名为inputChange
的函数:
<textarea value={this.state.text} onChange=...></textarea>
另一种方法是将其定义为箭头函数(称为类属性
?):
(我注意到的一点是,如果我们将inputChange
定义为箭头函数,我们可以将inputChange
视为this
的一个属性,当我们在内部打印this
时,例如,render
)
有人知道哪条路更好吗?一般来说,我们什么时候应该将React类中的函数定义为arrow函数?您需要绑定inputChange函数,以便它接收正确的上下文并能够使用此。setState 现在可以用多种方式绑定它 第一:
inputChange = (event) => {
let value = event.target.value;
this.setState((s) => ({ ...s, text: value }));
}
第二:在构造函数中使用bind
constructor(props) {
super(props);
this.inputChange = this.inputChange.bind(this)
}
inputChange(event){
let value = event.target.value;
this.setState((s) => ({ ...s, text: value }));
}
第三:内联绑定或箭头函数
inputChange (event) {
let value = event.target.value;
this.setState((s) => ({ ...s, text: value }));
}
...
<textarea value={this.state.text} onChange={this.inputChange.bind(this)}></textarea>
inputChange(事件){
让值=event.target.value;
this.setState((s)=>({…s,text:value}));
}
...
或
this.inputChange(e)}>
现在您必须注意,当您使用第三种方法内联绑定箭头函数时,会在每个渲染上创建一个新的函数引用,这将对性能产生非常轻微的影响。但是,如果您有许多这样的函数返回,那么性能影响将增加,这不仅是因为创建了更多的函数和需要垃圾收集,还因为使用PureComponent
或React.memo
实现的子组件优化将随着函数引用的更改而开始失败
您可以使用第一种或第二种绑定方法中的任何一种箭头函数可以方便地解决组件中的此问题。在传递回调函数时,您更经常会发现自己处于这种情况 现在,在这些情况下,不使用arrow函数可能会导致问题,因为您无法确定每次调用回调函数时this的值 因此,更好的方法是使用箭头函数。它们将这个关键字的值保留在函数内部,就像它在函数外部一样 这种方法解决了许多看不见的令人沮丧的bug,这些bug可能是由于关键字This的不正确用法和值引起的
要获得更详细的答案,请参阅文章中使用代码片段的解释。我知道我们有几种绑定方法可以让它工作。我想知道的是,像
inputChange
这样的函数定义哪个更有意义。@SoftTimur我想我在回答中确实提到过,你可以在函数中使用或绑定,或者将函数定义为箭头函数,因为两者的性能相似。在构造函数中使用绑定使用最少的内存
constructor(props) {
super(props);
this.inputChange = this.inputChange.bind(this)
}
inputChange(event){
let value = event.target.value;
this.setState((s) => ({ ...s, text: value }));
}
inputChange (event) {
let value = event.target.value;
this.setState((s) => ({ ...s, text: value }));
}
...
<textarea value={this.state.text} onChange={this.inputChange.bind(this)}></textarea>
<textarea value={this.state.text} onChange={(e) => this.inputChange(e)}></textarea>