javascript - 何时使用 function() 、 function 或 () => function(callback)

标签 javascript reactjs function ecmascript-6

我一直在寻找一个很好的解释,所以我很清楚。 示例:

<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/

相关文章:

javascript - 使用 CSS 或 JQuery 绘制 div 边框

javascript - firebase.database() 不是 react 中的函数错误

javascript - 单击 Material 表中的编辑图标访问

function - 柯里化(Currying)一个函数以获得另一个函数 : unit -> 'a

javascript - 页面重新加载时表单重置?

javascript - for 循环中的多个 setTimeout 调用

php - 在类中调用函数时触发事件

list - 最左边-最里面和最外面(Haskell)

javascript - 合并/展平数组数组

javascript - 在 React 应用程序中使用 <audio> 标签,在点击时播放所选文件