【问题标题】:How does an anonymous function work in onClick in React component?匿名函数如何在 React 组件中的 onClick 中工作?
【发布时间】:2021-08-04 08:00:01
【问题描述】:

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

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

案例一:

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

案例 2:

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

【问题讨论】:

    标签: reactjs onclick components


    【解决方案1】:
    const add = (x, y) => {
      return x + y
    }
    

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

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

    如果不传参数直接调用

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

    【讨论】:

      【解决方案2】:

      区别是

      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

      【讨论】:

        【解决方案3】:

        第一个将调用add(1, 2),并在单击按钮时将3返回给onClick属性的调用者。

        第二个将在 JSX 计算时调用 add(1, 2)(很可能在渲染期间),并将 3 作为 onClick 属性传递。情况2相当于:

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

        这很可能不是你想要的。

        你通常只会在函数返回另一个函数时调用这样的函数,例如:

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

        按下按钮时将记录 3。

        【讨论】:

          猜你喜欢
          • 2021-11-06
          • 1970-01-01
          • 1970-01-01
          • 2010-11-06
          • 2020-09-29
          • 2019-03-30
          • 2021-07-13
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多