我一直在寻找一个好的解释,所以对我来说一切都很清楚。示例:
<Char click={()=>this.onDeleteHandler(index)}/>vs
<Char click={this.onDeleteHandler()}/>vs
<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%!所以,如果你能为我提供一个解释,链接或类似的,那就太好了!
谢谢!
发布于 2018-06-26 17:40:28
<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的第一个参数传递
发布于 2018-06-26 18:05:34
整个问题似乎可以归结为func、func()和() => func()之间的区别。它与React没有特别的关系。
如果我有一个函数
function func() {
console.log(42);
}然后,我可以通过func引用函数对象本身。如果我需要将函数传递给另一个函数,例如setTimeout,这是很有用的
setTimeout(func, 1000); // calls func after 1000mssetTimeout期望在提供的超时之后可以调用的函数。
类似地,在React中,click、change等都是期望在事件发生时被传递给函数的道具。
另一方面,func()调用该函数。如果你真的需要当场调用函数,就需要这样做。这意味着如果我这样做了
setTimeout(func(), 1000);然后,我将首先调用func并将其返回值传递给setTimeout (即,我现在调用func,setTimeout稍后不会调用它)。所以这通常是不正确的,除非func返回一个函数本身,它实际上就是我想要传递给另一个函数的返回值。
() => func()只是一个只调用func的新函数。无论出于何种目的,它都等同于func
function func() {
console.log(42);
}
const anotherFunc = () => func();
func();
anotherFunc();
当然,如果func需要一个参数,那么在将它包装在另一个函数中时,我必须传递它,这就是x => func(x)所做的。
另一部分是分配给对象属性和this的函数是如何工作的。简而言之,this在(非箭头)函数中引用的内容取决于函数的调用方式。正在做什么
this.foo();
// or
var bar = this.foo;
bar();会产生两种不同的结果,因为this.foo()和bar()是两种不同的函数调用方式。有关更多信息,请参阅How to access the correct this inside a callback?
发布于 2018-06-26 17:48:05
通常,当您需要将处理程序绑定到上下文或提供自定义参数时,可以使用内联箭头函数
在……里面
<Char click={()=>this.onDeleteHandler(index)}/>onDeleteHandler被绑定到呈现Char的上下文,并被传递一个自定义参数index。由于新函数会返回到click,因此可以像this.props.click()一样在Char中执行
<Char click={this.onDeleteHandler()}/>在这里,计算onDeleteHandler并将值返回给click属性
<Person click={changed={(event) => this.nameChangedhandler(event, person.id)} />这里的语法是无效的,它可能应该是
<Person changed={(event) => this.nameChangedhandler(event, person.id)} />在这种情况下,它接受默认参数并将其与自定义参数一起传递给nameChangedHandler,并且还执行绑定
<Char click={this.onDeleteHandler}/>只是将onDeleteHandler的引用分配给click,每当您调用click时,都会使用您在调用click时传递的参数来调用onDeleteHandler,并且onDeleteHandler中的上下文将引用从中调用它的上下文,除非您使用箭头函数或在构造函数中绑定onDeleteHandler
https://stackoverflow.com/questions/51039568
复制相似问题