简体   繁体   English

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

[英]How does an anonymous function work in onClick in React component?

When there are two Button components in React, what is the difference between those two?当 React 中有两个 Button 组件时,这两者有什么区别?

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

Case 1:情况1:

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

Case 2:案例二:

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

The first one will call add(1, 2) and return 3 to the caller of the onClick prop when the button is clicked.第一个将调用add(1, 2)并在单击按钮时将 3 返回给onClick的调用者。

The second one will call add(1, 2) when the JSX is calculated (most likely during render), and will pass 3 as the onClick prop.第二个将在计算JSX 时调用add(1, 2) (很可能在渲染期间),并将3作为onClick传递。 Case 2 is equivalent to:案例 2 等价于:

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

which is very likely not what you want.这很可能不是您想要的。

You would usually invoke a function like that only when the function returns another function, eg:只有当 function 返回另一个function 时,您通常会像这样调用 function,例如:

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

which will log 3 when the button is pressed.按下按钮时将记录 3。

The differences are区别是

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

Case 1: this wait until the user click on the button it'll execute the call案例1:等到用户点击按钮,它会执行调用

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

Case 2: This implementation will give error案例2:这个实现会报错

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

Case 2.1: This case will bind the function to the click listener案例2.1:本案例将function绑定到点击监听

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

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

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

In order to pass a value as a parameter through the onClick handler we pass in an arrow function which returns a call to the add function.为了通过 onClick 处理程序将值作为参数传递,我们传入一个箭头 function,它返回对add function 的调用。

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

If no parameters are to be passed then you can call directly如果不传递任何参数,则可以直接调用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM