在JSX中嵌套if else条件

时间:2020-04-22 14:17:11

标签: javascript reactjs ecmascript-6 jsx

我正在尝试在JSX中编写嵌套的IF ELSE条件,但是它不起作用。谁能帮忙如何在JSX中编写以下条件?

if (content) {
    if (content.flag) {
        <showSomeComponent />
    }else if (!content.flag) {
        <showSomeOtherComponent />
    }
}

谢谢。

2 个答案:

答案 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 />;