接著要來認識React的條件判斷式,可以根據不條件,來給組件回傳不同的網頁內容
而判斷式中有幾個常見的用法,首先是三元運算子(ternary operator)
function App() {
return(true ? <h1>hello</h1> : <h1>world</h1>)
} //return hello
function App() {
return(false ? <h1>hello</h1> : <h1>world</h1>)
} //return world
三元運算式的另一種應用是把它寫到html元素裡
function App() {
return(
<div className="my-div"> //給定一個class
{true ? <h1>hello</h1> : <h1>world</h1>}
</div>
)
}
有時為了想給元素切換不同的css,會在className裡使用三元運算式
<div className={false ? 'a ' : 'b'}>
元素通常不只有一個class,而是有好幾個class。而有些class是固定不變的,有些則會改變,所以可以直接把會固定不變的class加在字串裡(c)
<div className={false ? 'a c ' : 'b c'}>
或是更進階一點使用反引號字串 { c ${}
}
<div className={`c ${true ? 'a' : 'b'}`}> //顯示c a
<div className={`c ${false ? 'a' : 'b'}`}> //顯示c b
在JavaScript當中,AND邏輯運算通常會出現在if判斷式中。狹義上的功能,只有兩邊的算式都是true時,AND邏輯運算才會回傳true,否則回傳false。廣義上來說,AND邏輯運算式的功能為:當AND左邊的值是真值(true)時,則會回傳右邊的值;反之則回傳左邊的值。
若要應用,可以利用AND邏輯院算決定是否要展示元素
{true && <h1>hello</h1>} //顯示hello
{false && <h1>hello</h1>} //沒有顯示東西
學習影片出處:https://youtu.be/aBTiZfShe-4?si=Igb2aKz3sefA97A5