何时使用function(),function或()=> function(callback)

Mic*_*ael 3 javascript function ecmascript-6 reactjs

我一直在寻找一个很好的解释,所以这一切都清楚了.例:

<Char click={()=>this.onDeleteHandler(index)}/>
Run Code Online (Sandbox Code Playgroud)

VS

<Char click={this.onDeleteHandler()}/>
Run Code Online (Sandbox Code Playgroud)

VS

<Person changed={(event) => this.nameChangedhandler(event, person.id)} />
Run Code Online (Sandbox Code Playgroud)

<Char click={this.onDeleteHandler}/>
Run Code Online (Sandbox Code Playgroud)

关于第三个代码,这里是名为:

nameChangedhandler = (event, id) => {
const personIndex = this.state.persons.findIndex(p => {
  return p.id === id;
});

// copying the person with the right index
const person = {
  ...this.state.persons[personIndex]
};

// Assigning new name to this person
person.name = event.target.value;

// copying array of persons, then manipulating the correct object of person by using the index
const persons = [...this.state.persons];
persons[personIndex]= person;

this.setState({
  persons: persons
});
Run Code Online (Sandbox Code Playgroud)

}

有些方面对我来说很清楚,但绝对不是100%!所以,如果你能给我一个解释,链接或类似的东西,那将是伟大的!

谢谢!

hsz*_*hsz 7

<Char click={()=>this.onDeleteHandler(index)}/>
Run Code Online (Sandbox Code Playgroud)

它将匿名函数作为回调传递 - 当被点击时 - 触发onDeleteHandler额外index参数(必须在之前的范围内定义).

<Char click={this.onDeleteHandler()}/>
Run Code Online (Sandbox Code Playgroud)

它传递onDeleteHandler()作为回调的结果- 可能是个坏主意 - onDeleteHandler函数必须返回另一个将在点击时调用的函数.

<Person click={changed={(event) => this.nameChangedhandler(event, person.id)} />
Run Code Online (Sandbox Code Playgroud)

看起来无效 - 会导致语法错误.

<Char click={this.onDeleteHandler}/>
Run Code Online (Sandbox Code Playgroud)

与第一个示例类似,但不采用自定义参数.默认点击事件将作为第一个参数传递onDeleteHandler