匿名函数如何在 React 组件的 onClick 中工作?

How does an anonymous function work in onClick in React component?

当 React 中有两个 Button 组件时,这两者有什么区别?

const add = (x, y) => {
  return x + y
}

案例 1:

<Button onClick={() => add(1, 2)}>Add</Button>

案例二:

<Button onClick={add(1, 2)}>Add</Button>

单击按钮时,第一个将调用 add(1, 2) 和 return 3 到 onClick 道具的调用者。

第二个将在计算 JSX 时调用add(1, 2)(最有可能在渲染期间),并将3 作为[=14] =] 道具。情况 2 相当于:

<Button onClick={3}>Add</Button>

这很可能不是您想要的。

只有当函数 return 是 另一个 函数时,您通常会调用这样的函数,例如:

const logNums = (x, y) => () => {
  console.log(x + y);
}
<Button onClick={logNums(1, 2)}>Add</Button>

按下按钮时将记录 3。

区别是

const add = (x, y) => {
  return x + y
}

案例 1:等待用户点击按钮,它会执行调用

<Button onClick={() => add(1, 2)}>Add</Button>

情况2:这个实现会报错

<Button onClick={add(1, 2)}>Add</Button>

案例2.1:该案例将函数绑定到点击监听器

<Button onClick={add}>Add</Button>

参考:https://medium.com/@omergoldberg/javascript-call-apply-and-bind-e5c27301f7bb

const add = (x, y) => {
  return x + y
}

为了通过 onClick 处理程序传递一个值作为参数,我们传入一个箭头函数,该函数 returns 调用 add 函数。

<Button onClick={() => add(1, 2)}>Add</Button>

如果不传参数可以直接调用

const add=()=>{
    return 2+3
}
<Button onClick={add}>Add</Button>