[英]Conditional rendering with && operator within react return statement
當我的條件使用&&運算符時,如何在類組件中構造return語句,如下所示:
if (x === null && y === null)
...然后顯示此html:
<div className="col-12">
<SomeComponent />
</div>
否則顯示此html:
<div className="col-6">
<SomeOtherComponent />
</div>
<div className="col-6">
<SomeOtherComponent />
</div>
我需要將它放在return語句中,因為我將整個條件包裝在<main><div className="row></div></main>
包裝器中,如下所示:
<main>
<div className="row">
// show the above mentioned html conditionally
</div>
</main>
您應該使用簡寫if語句<condition> ? <if true> : <if false>
<condition> ? <if true> : <if false>
。 您的退貨聲明應如下所示。
return (
<main>
{x === null && y === null ? (
<div className="row">
<div className="col-12">
<SomeComponent />
</div>
</div>
) : (
<div className="row">
<div className="col-6">
<SomeOtherComponent />
</div>
<div className="col-6">
<SomeOtherComponent />
</div>
</div>
)}
</main>
);
這是使用三元運算符的方法: {condition ? (if condition is true ) : (if condition is false)}
{condition ? (if condition is true ) : (if condition is false)}
<main>
<div className="row">
{x === null && y === null ? (
<div className="col-12">
<SomeComponent />
</div>): (<div className="col-6">
<SomeOtherComponent />
</div>
<div className="col-6">
<SomeOtherComponent />
</div>)}
</div>
</main>
您可以使用三元運算符:
(x === null && y === null) ? (render if true) : (render this if false)
另外,null是偽造的值,因此您可以編寫(!x && !y)
。
如果要使用ifs編寫,請調用this.renderComponent()
類的方法並解析其中的所有內容,然后返回值或整個組件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.