如何在反应中使用if语句?

清洁

我有一个.jsx文件,其中包含:

<p_grid>
  <RangeSpan>
    Currently, there are {" "}
    <b>{Math.round(house.records * 100) / 100} houses</b> found.
  </RangeSpan>
</p_grid>

这项工作正常,但现在我要审讯house.source并显示不同的内容,例如:

if ({house.source}=="X")
{
Currently, there are {" "} <b>{Math.round(house.records * 100) / 100} houses</b> found.
}
else
{
different calculation and text.
}

我可以显示house.sourceOK,但无法弄清楚if语句的执行方式。对此完全陌生,因此不胜感激(我尝试使用三元运算符,但不知道如何与它结合使用{}""甚至不知道在这种情况下都可以使用)。

亚历山大·尼德

您不能在JSX中直接使用if/else语句,但是可以执行以下操作:

<p_grid>
  <RangeSpan>
    {
        house.source === "X"
        && (<>Currently, there are {" "} <b>{Math.round(house.records * 100) / 100} houses</b> found.</>)
    }
    {
        house.source !== "X"
        && (<>different calculation and text.</>)
    }
  </RangeSpan>
</p_grid>

如TKol的回答所示,这也可以表示为三元

如果涉及的更多,则可以将计算移至实际JSX return语句之外的render方法(或功能组件)中,甚至将功能封装到其自己的组件中(Prebiusta的答案就是一个很好的例子。方法)。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章