reactjs - 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?
解决方案
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)}
推荐阅读
- mongodb - Mongo DB 连接 - 密码包含未转义字符
- macos - 如何使用 nix-darwin 为多用户设置选项“system.defaults.dock.autohide”?
- css - VS Code 不会保存 vuetify.css 文件
- python - 正则表达式用于任何结尾的确切电话号码
- html - 使用用户界面,nearpoint/renderprint/verbatimTextOutput('print') 在用户点击时显示部分变量
- html - 添加滚动条时如何修复未对齐的引导列
- python - 如何在“外星人入侵”中制作难度按钮?
- python - 当测试用例断言失败时,tearDown 不会在 python selenium 上执行
- kubernetes - 当作业控制的 pod 由于内存不足错误而失败时,如何最好地在重新启动 pod 之前增加请求的内存?
- mongodb - 邮递员发送请求挂起