您好,当我在前端有条件输出时,是否也可以创建 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/