问题描述
我想知道是否有可能在reactjs
jsx
中嵌套吗?
I wanted to know if its possible to do nested if else if in reactjs
jsx
?
我尝试了各种不同的方法,但无法使其正常工作.
I have tried various different ways and I am unable to get it to work.
我正在寻找
if (x) {
loading screen
} else {
if (y) {
possible title if we need it
}
main
}
我已经尝试过了,但是无法渲染.我尝试了各种方法.一旦添加嵌套的if,它总是会中断.
I have tried this but I can not get it to render. I have tried various ways. It always breaks once I add the nested if.
{
this.state.loadingPage ?
(<div>loading page</div>) :
(<div>
this.otherCondition && <div>title</div>
<div>body</div>
</div>)
}
更新
我最终选择了将其移至renderContent并调用该函数的解决方案.这两个答案都确实有效.我想我可以使用内联解决方案,如果它用于简单的render和renderContent来处理更复杂的情况.
I ended up choosing the solution to move this to renderContent and call the function. Both of the answers did work though. I think I may use the inline solution if it is for a simple render and renderContent for more complicated cases.
谢谢
推荐答案
您需要将标题和正文包装在容器中.那可能是一个div.如果改用列表,则dom中的元素要少一个.
You need to wrap your title and body in a container. That could be a div. If you use a list instead, you'll have one less element in the dom.
{ this.state.loadingPage
? <span className="sr-only">Loading... Registered Devices</span>
: [
(this.state.someBoolean
? <div key='0'>some title</div>
: null
),
<div key='1'>body</div>
]
}
我建议不要嵌套三元语句,因为它很难阅读.有时早退"比使用三元组更为优雅.另外,如果只需要三元组的真正部分,则可以使用isBool && component
.
I would advise against nesting ternary statements because it's hard to read. Sometimes it's more elegant to "return early" than to use a ternary. Also, you can use isBool && component
if you only want the true part of the ternary.
renderContent() {
if (this.state.loadingPage) {
return <span className="sr-only">Loading... Registered Devices</span>;
}
return [
(this.state.someBoolean && <div key='0'>some title</div>),
<div key='1'>body</div>
];
}
render() {
return <div className="outer-wrapper">{ renderContent() }</div>;
}
注意语法someBoolean && "stuff"
:如果错误地将someBoolean
设置为0
或NaN
,则该Number将呈现给DOM.因此,如果布尔值"可能是虚假数字,则使用(someBoolean ? "stuff" : null)
更为安全.
Caveat to the syntax someBoolean && "stuff"
: if by mistake, someBoolean
is set to 0
or NaN
, that Number will be rendered to the DOM. So if the "boolean" might be a falsy Number, it's safer to use (someBoolean ? "stuff" : null)
.
这篇关于如何在reactjs JSX中嵌套if语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!