何时使用function(),function或()=>函数(回调) [英] when to use function() , function or () => function(callback)
问题描述
我一直在寻找一个好的解释,所以这一切都清楚了。
示例:
I have been searching for a while for a good explanation so its all clear to me. Example:
<Char click={()=>this.onDeleteHandler(index)}/>
vs
<Char click={this.onDeleteHandler()}/>
vs
<Person changed={(event) => this.nameChangedhandler(event, person.id)} />
和
<Char click={this.onDeleteHandler}/>
关于第三个代码,这里是名为:
regarding the third code , here is the property called:
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%!
所以如果你能给我一个很好的解释,链接或类似的信息!
some aspects are clear to me, but definitely not 100%! So if you can provide me with an explanation, link or similar that would be great!
谢谢!
推荐答案
<Char click={()=>this.onDeleteHandler(index)}/>
它将匿名函数作为回调传递 - 当点击时 - 触发 onDeleteHandler
带有额外的 index
参数(必须在之前的范围内定义)。
It passes anonymous function as a callback which - when clicked - triggers onDeleteHandler
with extra index
parameter (which has to be defined in the scope before).
<Char click={this.onDeleteHandler()}/>
它传递 onDeleteHandler()
的结果为一个回调 - 可能是一个坏主意 - onDeleteHandler
函数必须返回另一个将在点击时调用的函数。
It passes result of onDeleteHandler()
as a callback - probably a bad idea - onDeleteHandler
function has to return another function that will be invoked on click.
<Person click={changed={(event) => this.nameChangedhandler(event, person.id)} />
看起来无效 - 会导致语法错误。
Looks invalid - will result with syntax error.
<Char click={this.onDeleteHandler}/>
与第一个示例类似但不采用自定义参数。默认点击事件将作为 onDeleteHandler的第一个参数传递
Similar to the first example but doesn't take custom parameters. Default click event will be passed as a first argument for onDeleteHandler
这篇关于何时使用function(),function或()=>函数(回调)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!