Skip to main content

Conditional Rendering 條件渲染

加上條件

{
coins > 0 && <homeServiceSection />;
}

1. Using an if…else Statement#

頁面看不出結構 邏輯渲染綁得看死

let section;
if (coin > 0) {
section = <HomeBannerSection>hi</HomeBannerSection>;
} else if (coin === 0) {
section = <HomeImageSection />;
} else {
section = <HomeImageSection />;
}
{
seciton;
}

2.Using Ternary Operators 三元運算子#

{
coins > 0 ? <HomeBannerSection/>: coins === 0 ? <HomeImageSection/>:coins < 0 ? <HomeTitleSection/>
}

3.Using Logical && (Short Circuit Evaluation)#

拆開寫

{
coins > 0 && <homeServiceSection />;
}
{
coins === 0 && <HomeImageSection />;
}

拆出來寫#

<HomeConditoinSection coins={coins}>
const HomeConditoinSection ={{coins}}=> {
if (coins > 0) {
return(
<HomeBannerSection/>
);
}
if (coins ==== 0) {
return(
<HomeImgSection/>
);
}
return <HomeTitleSection/>
}