我正在尝试在JSX中编写嵌套的IF ELSE条件,但是它不起作用。谁能帮忙如何在JSX中编写以下条件?
if (content) {
if (content.flag) {
<showSomeComponent />
}else if (!content.flag) {
<showSomeOtherComponent />
}
}
谢谢。
答案 0 :(得分:2)
您需要一个return
语句和Uppercased component name:
if (content) {
if (content.flag) {
return <ShowSomeComponent />;
} else {
return <ShowSomeOtherComponent />;
}
}
注意:组件名称始终以大写字母开头。 React将以小写字母开头的组件视为DOM标签。
或带有可选的链接和三元运算符:
// return content && content.flag ? <ShowSomeComponent /> : <ShowSomeOtherComponent />
return content?.flag ? <ShowSomeComponent /> : <ShowSomeOtherComponent />;
答案 1 :(得分:1)
您可以在
中编写它const asd = content && content.flag ? <ShowSomeComponent /> : <ShowSomeOtherComponent />
const asd = content && content.flag && <ShowSomeComponent /> || <ShowSomeOtherComponent />
return content && content.flag && <ShowSomeComponent /> || <ShowSomeOtherComponent />
return content?.flag ? <ShowSomeComponent /> : <ShowSomeOtherComponent />;