javascript else if JSX 中的情况

标签 javascript reactjs

您好,当我在前端有条件输出时,是否也可以创建 else if () 语句?

当前代码如下所示:

    {this.props.contentComponentData.typeOf === 1
      &&
      <ContentComponentChecklistInstances
            checklistItems={this.props.contentComponentData.checklists}
      />
     }

提前致谢

最佳答案

您可以使用conditional operator制作 if/else 表达式:

{someCondition === true ? (
    <TrueComponent/>
) : (
    <FalseComponent/>
)}

如果您想要 if/elseif/else,您可以将多个条件组合在一起:

{someCondition === true ? (
    <IfComponent/>
) : someOtherCondition === true ? (
    <ElseIfComponent/>
) : (
    <ElseComponent/>
)}

这些内容可能很难阅读,因此您应该考虑使用正常的 if 和 else 将此代码放在 return 语句之上:

let component;
if (someCondition === true) {
    component = <IfComponent/>
} else if (someOtherCondition === true) {
    component = <ElseIfComponent/>
} else {
    component = <ElseComponent/>
}

return (
  <div>{component}</div>
);

关于javascript else if JSX 中的情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46665510/

相关文章:

javascript - 我如何有条件地在 Angular js中应用标题

javascript - Javascript 的正则表达式获取子字符串

javascript - 使花式框透明

javascript - 如何处理竞争条件

javascript - 光标 :pointer not working for <Link> in React

javascript - Reactjs 添加一个对象到状态

javascript - 无法更改文本字段变体的边框半径 = 在 Material-ui-core 中填充

javascript - 使用无限滚动和 WP 进行触摸导航

javascript - Redux 容器不知道 "this"是什么

reactjs - 从组件外部设置 React 组件状态