reactjs 三值运算符的实现使两个条件都起作用

xzlaal3s  于 2022-12-12  发布在  React
关注(0)|答案(5)|浏览(144)

我尝试使用三元运算符在react中实现条件渲染,但是我似乎不能正确使用语法。下面是我的结果:

const [isDeleted, setIsDeleted] = useState(false);

我有一个删除用户的功能:

const deleteUser = () => {
    axios.post("http://localhost:5000/delete", []).then((resp) => {
      setIsDeleted(resp.data);
      isDeleted(true);
    });
  };

我调用下面的deleteUser函数onclick,它将isDeleted更改为true。

<Box>
            <Button
              sx={{
                padding: "10px 20px",
              }}
              onClick={deleteUser}
            >
              Delete User
            </Button>
          </Box>

下面,如果isdeleted为true,则使用三元运算来呈现successfully deleted,如果isdeleted为false,则显示Hello User。我所拥有的只是将其打印在屏幕上。我似乎无法获得正确的语法。

<Typography
                fontWeight="bold"
              >
                isDeleted? Successfully Deleted : Hello User
              </Typography>
4uqofj5v

4uqofj5v1#

使用{} Package 语句

{ isDeleted ? <>Successfully Deleted</> : <>Hello User</>}
eufgjt7s

eufgjt7s2#

缺少括号

<Typography fontWeight="bold">
    {isDeleted? "Successfully Deleted" : "Hello User"}
</Typography>
o8x7eapl

o8x7eapl3#

请尝试以下操作:

<Typography fontWeight="bold">
     {isDeleted ? `Successfully Deleted` : `Hello User`}
  </Typography>
mbyulnm0

mbyulnm04#

Ternary是JavaScript表达式。所有此类表达式都应括在方括号{}内:

<Typography fontWeight="bold">
  {isDeleted ? "Successfully Deleted" : "Hello User"}
</Typography>
vnzz0bqm

vnzz0bqm5#

isDeleted是一个属性,您应该使用setIsDeleted(resp.data);方法

相关问题