当 React 中有两个 Button 组件时,这两者有什么区别?
const add = (x, y) => {
return x + y
}
案例一:
<Button onClick={() => add(1, 2)}>Add</Button>
案例二:
<Button onClick={add(1, 2)}>Add</Button>
最佳答案
第一个将调用 add(1, 2)
并在单击按钮时将 3 返回给 onClick
属性的调用者。
第二个将在 计算 JSX 时调用 add(1, 2)
(最有可能在渲染期间),并将传递 3
作为 onClick
Prop 。情况 2 相当于:
<Button onClick={3}>Add</Button>
这很可能不是您想要的。
通常只有当函数返回另一个函数时,您才会调用这样的函数,例如:
const logNums = (x, y) => () => {
console.log(x + y);
}
<Button onClick={logNums(1, 2)}>Add</Button>
按下按钮时将记录 3。
关于reactjs - 匿名函数如何在 React 组件的 onClick 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67529332/