首页 > 解决方案 > simple questions of callbacks with and without an array function

问题描述

i have a simple question that has border me for a very long time. so can anyone tell me what is the difference between onClick{()=> function()}} and onClick{function()}? what is the difference between having a arrow function and without an arrow function? and are these two function both callback functions?

标签: reactjscallback

解决方案


onClick={() => callback()}我相信您的意思更多的是和onClick={callback}注意sans())之间的区别。如果你这样做了,onClick={callback()}那么回调将立即被调用,而不是在点击发生时。

  • onClick={() => callback()}: 每次渲染组件时都会创建一个匿名函数
  • onClick={callback}:每个渲染周期都会传递对回调函数的“引用”

除了使用直接引用版本之外,两者之间没有太大区别,它也被传递onClick事件,但如果回调无论如何都不接受任何参数,这不是问题。使用匿名函数可能会占用更高的内存(因为每个组件都会收到回调的副本),并且在构建副本时会影响一些边际性能。

使用匿名回调函数允许传递其他参数

onClick={() => callback(customArg)}

或者您可以代理事件对象传递其他参数

onClick={event => callback(event, customArg)}

您可以通过创建curried回调函数,通过直接引用实现类似的效果。这允许您仍然传递其他参数事件onClick

const callback = customArg => event => {...}
...
onClick={callback(customArg)}

推荐阅读