【问题标题】:jsx: ReactJS if conditionjsx: ReactJS if 条件
【发布时间】:2021-08-13 08:21:28
【问题描述】:

如何在jsx中使用if条件:ReactJS?我只是想要,如果

if user == "author" or "supervisor":
<IconButton 
   aria-label="delete" 
   onClick={() => props.pressHandler(props.id)}
 >
  <DeleteIcon style={{ color: 'red' }} />
</IconButton>
else
     no delete button

【问题讨论】:

标签: reactjs react-native jsx


【解决方案1】:

只要把它们放在大括号里,

{ ["author", "supervisor"].includes(user) &&
<IconButton 
   aria-label="delete" 
   onClick={() => props.pressHandler(props.id)}
 >
  <DeleteIcon style={{ color: 'red' }} />
</IconButton> || null }

参考:https://reactjs.org/docs/conditional-rendering.html#inline-if-with-logical--operator

【讨论】:

    【解决方案2】:

    详细说明斯塔克写的内容:

    你可以这样使用js操作符:

    {(
     (user === "author" || user === "supervisor") && 
    <IconButton 
       aria-label="delete" 
       onClick={() => props.pressHandler(props.id)}
     >
      <DeleteIcon style={{ color: 'red' }} />
    </IconButton>
    ) || undefined
    }
    

    三元运算符和 React Fragment 同上:

    {
    (user === "author" || user === "supervisor") ?
    <IconButton 
       aria-label="delete" 
       onClick={() => props.pressHandler(props.id)}
     >
      <DeleteIcon style={{ color: 'red' }} />
    </IconButton> : <></>
    }
    

    在 false 情况下,UndefinedReact.Fragment 不会被渲染。

    【讨论】:

      【解决方案3】:
      {
        ["author", "supervisor"].includes(user) ? (
          <IconButton
            aria-label="delete"
            onClick={() => props.pressHandler(props.id)}
          >
            <DeleteIcon style={{ color: "red" }} />
          </IconButton>
        ) : null;
      }
      

      当您使用“&&”运算符时,有时您会在应用程序上看到“假”文本。 null 将是不显示任何内容的绝佳选择,或者使用可以将与普通用户的删除按钮不同的内容设置为 null。

      【讨论】: