admin 管理员组文章数量: 1086019
Hi when I have a condition output in frontend is there a possibility to make a else if ()
statement as well?
current code looks like:
{this.props.contentComponentData.typeOf === 1
&&
<ContentComponentChecklistInstances
checklistItems={this.props.contentComponentData.checklists}
/>
}
Thanks in advance
Hi when I have a condition output in frontend is there a possibility to make a else if ()
statement as well?
current code looks like:
{this.props.contentComponentData.typeOf === 1
&&
<ContentComponentChecklistInstances
checklistItems={this.props.contentComponentData.checklists}
/>
}
Thanks in advance
Share Improve this question edited Oct 10, 2017 at 11:28 Icepickle 12.8k3 gold badges37 silver badges50 bronze badges asked Oct 10, 2017 at 11:23 FelixFelix 5,62614 gold badges80 silver badges173 bronze badges 1-
Yeah, but you have to use a ternary operator. Or, you write the inverse condition and do your if block. Ternary opeartor would rather be like
condition ? iftrue : iffalse
. A better way to go about this however would be to extract your condition to a variable, and simply render the variable though, not need to pollute the visual tree – Icepickle Commented Oct 10, 2017 at 11:26
3 Answers
Reset to default 7You can use the conditional operator to make if/else expressions:
{someCondition === true ? (
<TrueComponent/>
) : (
<FalseComponent/>
)}
If you want an if/elseif/else, you can bine multiple conditionals together:
{someCondition === true ? (
<IfComponent/>
) : someOtherCondition === true ? (
<ElseIfComponent/>
) : (
<ElseComponent/>
)}
These things can be difficult to read, so you should consider pulling this code up above your return statement, using normal if's and elses:
let ponent;
if (someCondition === true) {
ponent = <IfComponent/>
} else if (someOtherCondition === true) {
ponent = <ElseIfComponent/>
} else {
ponent = <ElseComponent/>
}
return (
<div>{ponent}</div>
);
{this.props.contentComponentData.typeOf === 1
&&
<ContentComponentChecklistInstances
checklistItems={this.props.contentComponentData.checklists}
/>
|| condition && ifConditionMetExpression
}
But this is a bit hard to read, I suggest you use ternaries instead:
{this.props.contentComponentData.typeOf === 1
? <ContentComponentChecklistInstances
checklistItems={this.props.contentComponentData.checklists}
/>
: condition
? ifConditionMetExpression
: null
}
(first condition)
? // if first condition true this part run
: (second condition)
? // if second condition true this part run
: // else part
本文标签: reactjsjavascript elseif case in JSXStack Overflow
版权声明:本文标题:reactjs - javascript elseif case in JSX - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1744039330a2522964.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论