【问题标题】:how to apply tarnary operator on single button onClick event in React如何在 React 中的单个按钮 onClick 事件上应用三元运算符
【发布时间】:2023-01-13 18:28:39
【问题描述】:

你好开发社区我遇到了一个问题,需要你的帮助。

我正在尝试将单个按钮组件用于多种用途,这里出现了问题。

在深入探讨这个问题之前,我想简化我的要求如下:

所以我想根据布尔变量执行多个操作是真的如果这个变量是真的我想打印真 否则打印假

这是我尝试使用按钮组件的文件的代码:

         
<Button            
  handleClick={`${props.openForAddUser?handleAddUser():handleUpdate()}`}           
  buttonText={`${props.openForAddUser?"Add New User":"Update"}`}
/>

function handleAddUser(){
    alert("handle add new user");
}
function handleUpdate() {
   alert("handle update");
}

如果您想了解 Button 组件,这里是该组件的代码。

const Button = (props) => {
  return (
    <>
      <span className="flex flex-col items-center justify-center">
        <button
          
          type="submit"
          className={props.className}
          onClick={props.handleClick} // here the conditional callback function took place
        >
          {props.buttonText}
        </button>
      </span>
    </>
  );
};

export default Button;

```




Note: the only solution i am looking for is to add multiple function for single onClick event.

【问题讨论】:

    标签: javascript reactjs onclick conditional-operator


    【解决方案1】:

    尝试这个

    <Button            
      handleClick={props.openForAddUser ? handleAddUser : handleUpdate}           
      buttonText={props.openForAddUser ? "Add New User" : "Update"}
    />
    
    function handleAddUser(){
        alert("handle add new user");
    }
    function handleUpdate() {
       alert("handle update");
    }
    

    【讨论】:

      猜你喜欢
      • 2015-05-15
      • 2022-01-04
      • 2021-06-30
      • 1970-01-01
      • 2015-12-15
      • 2021-12-15
      • 2021-11-20
      • 2021-10-02
      • 1970-01-01
      相关资源
      最近更新 更多