我们何时应该在React类中将函数定义为箭头函数?

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类中将函数定义为箭头函数?

评论
  • cet
    cet 回复

    You would need to bind the inputChange function in order for it to receive the correct context and be able to use this.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>
    

    要么

    <textarea value={this.state.text} onChange={(e) => this.inputChange(e)}></textarea>
    

    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 or React.memo will start to fail as the function reference changes

    您可以使用第一种或第二种方法进行绑定