JSX:ReactJS中的条件语句

4
如何在JSX中使用条件语句:ReactJS?我只想要当某个变量为真时,渲染出特定的内容,否则不渲染任何内容。
if user == "author" or "supervisor":
<IconButton 
   aria-label="delete" 
   onClick={() => props.pressHandler(props.id)}
 >
  <DeleteIcon style={{ color: 'red' }} />
</IconButton>
else
     no delete button

https://reactjs.org/docs/conditional-rendering.html - Yossi
3个回答

5

1

为了阐述Stark所写的内容:

您可以使用以下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> : <></>
}

在错误的情况下,UndefinedReact.Fragment不会被渲染。

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

当您使用“&&”运算符时,有时会在应用程序中看到“false”文本。null将是显示空白或用户可以放置与删除按钮不同的内容的好选择。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接