簡體   English   中英

如何有條件地渲染兩個 JSX 變量?

[英]How can I render two JSX variables conditionally?

我有兩個 JSX 變量,我需要有條件地渲染它們。 這些是我的變量:

 const example1= (<div className="row">
             <p>TEST1</p>
             </div>);
 const example2= (<div className="row">
             <p>TEST1</p> 
             </div>);

我需要渲染example1然后example1 && example2

我怎樣才能在 JSX 中做到這一點?

這個有效。

{this.state.input === "1" && example1}

這個不行

{this.state.input === "2" && example1 && example2}
{this.state.input === "2" ? (example1 && example2) : null}

有任何想法嗎??

如果你想同時展示,試試這個

{this.state.input === "2" ? <>{example1}{example2}</> : ""}
{this.state.input === "1" && example1}
{this.state.input === "2" && (
  <React.Fragment>
    {example1}
    {example2}
  </React.Fragment>
)}

如果您願意,可以使用<> </>作為<React.Fragment> </React.Fragment>的簡寫

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM