I'm creating a web page using React. There is a textarea
where we could input a text. Thus, inside return
, onChange
is linked to a function named inputChange
:
<textarea value={this.state.text} onChange=...></textarea>
Regarding inputChange
, one way is to define it as a method (called object method
?):
inputChange (event) {
let value = event.target.value;
this.setState((s) => ({ ...s, text: value }));
}
Another way is to define it as an arrow function (called class property
?):
inputChange = (event) => {
let value = event.target.value;
this.setState((s) => ({ ...s, text: value }));
}
有谁知道哪种方法更好?通常,我们何时应该在React类中将函数定义为箭头函数?
You would need to bind the inputChange function in order for it to receive the correct context and be able to use
this.setState
现在您可以通过多种方式绑定它
第一:
第二:在构造函数中使用bind
第三:内联绑定或箭头功能
要么
Now you must note that when you bind the arrow function inline using the Third method, a new function reference is created on each render and it would have a very slight performance impact. However if you have many such functions returns, the performance impact will grow, not just because of more functions being created and a need for garbage collection, but because the child component optimization if any implemented using
PureComponent
orReact.memo
will start to fail as the function reference changes您可以使用第一种或第二种方法进行绑定