0%

React — 條件渲染 (Conditional Rendering)

React — 條件渲染(Conditional Rendering)

條件渲染 (Conditional Rendering) 定義

  • 讓元件依循條件做屬性、內容、配置更動
  • 配合Reactjs的資料單向流模式,讓狀態更可預期
  • 因為元件即方法,直接將判斷式寫在方法中
  • 可以配置"文字內容"、“樣式改變”、“屬性(props)”、“顯示路由(React route)

實作

1
2
3
4
5
6
7
8
9
10
function ConditionDescription(props) {
console.log('props =>', props); // props因為下面有設定gender屬性,所以會帶有gender屬性
if(props.gender === 'boy') {
return <p style={props.useStyle ? {color: 'blue'} : {}}>Hello, boy</p>
} else if(props.gender === 'girl') {
return <p style={props.style}>Hello, girl</p>
} else {
return <p>Hello, world</p>
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
function App() {
if(window.location.pathname === '/') {
return (
<div className="App">
<header className="App-header">
<MyImg className="App-logo" />
<ConditionDescription
gender="girl"
style={{ color: 'red' }}
/>
<Description
name="Amy"
age="18"
/>
<AppLink className="App-link" href="https://reactjs.org" />
</header>
</div>
);
} else if(window.location.pathname === '/pure') {
return (
<div className="App">
<header className="App-header">
<MyImg className="App-logo" />
<ConditionDescription
gender="boy"
useStyle={true}
/>
<Description
name="Ivan"
age="18"
/>
<AppLink className="App-link" href="https://reactjs.org" />
</header>
</div>
);
}
}

💁‍♀️ ConditionDescription的props物件

  • Pathname === / : props = {gender: 'girl', style: {color: 'red'}}
  • Pathname === /pure : props = {gender: 'boy', useStyle: true}

畫面的呈現及配置重點說明

Pathname: '/'

react

Pathname: '/pure'

react

🔎 參考資料