我一直在寻找一个很好的解释,所以我很清楚。 示例:
<Char click={()=>this.onDeleteHandler(index)}/>
对比
<Char click={this.onDeleteHandler()}/>
对比
<Person changed={(event) => this.nameChangedhandler(event, person.id)} />
和
<Char click={this.onDeleteHandler}/>
关于第三个代码,这里是属性调用:
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
});
有些方面我是清楚的,但绝对不是100%! 因此,如果您能向我提供解释、链接或类似信息,那就太好了!
谢谢!
最佳答案
<Char click={()=>this.onDeleteHandler(index)}/>
它将匿名函数作为回调传递,点击时会触发带有额外 index
参数(必须在之前的范围中定义)的 onDeleteHandler
。
<Char click={this.onDeleteHandler()}/>
它将 onDeleteHandler()
的结果作为回调传递 - 可能是个坏主意 - onDeleteHandler
函数必须返回另一个将在点击时调用的函数。
<Person click={changed={(event) => this.nameChangedhandler(event, person.id)} />
看起来无效 - 将导致语法错误。
<Char click={this.onDeleteHandler}/>
与第一个示例类似,但不采用自定义参数。默认点击事件将作为第一个参数传递给 onDeleteHandler
关于javascript - 何时使用 function() 、 function 或 () => function(callback),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51039568/