Conditional Rendering簡單來說就是利用if或是conditional operator(三元運算子)來進行有條件式的描繪。主要運用我們先前提的state,因為state封裝在component裡用來表示目前的狀態,判斷state條件式的描繪。我們也可以從外部或者父元件傳參數進來,利用props來進行條件的判斷。
下例範例,睡覺時打開鬧鐘起床關閉鬧鐘,主要針對if和conditional operator進行撰寫,可以注意觀察state和props的用法。
src/AlarmClockControl.js
import React, { Component } from 'react';
class AlarmClockControl extends React.Component {
constructor(props) {
super(props);
this.OpenAlarmClockClick = this.OpenAlarmClockClick.bind(this);
this.CloseAlarmClockClick = this.CloseAlarmClockClick.bind(this);
this.state = {isAlarm: false};
}
OpenAlarmClockClick() {
this.setState({isAlarm: true});
}
CloseAlarmClockClick() {
this.setState({isAlarm: false});
}
render() {
const isAlarm = this.state.isAlarm;
let button = null;
if (isAlarm) {
button = <ClockAlarmButton ring="off" onClick={this.CloseAlarmClockClick} />;
} else {
button = <ClockAlarmButton ring="on" onClick={this.OpenAlarmClockClick} />;
}
return (
<div>
<Action isAlarm={isAlarm} />
{button}
</div>
);
}
}
function Morning(props) {
return <h1>Get up!</h1>;
}
function Night(props) {
return <h1>Sleep zzz...</h1>;
}
function Action(props) {
const isAlarm = props.isAlarm;
if (isAlarm) {
return <Morning />;
}
return <Night />;
}
function ClockAlarmButton(props) {
return (
<button onClick={props.onClick}>
{props.ring==='on'?'Open Alarm Clock': 'Close Alarm Clock'}
</button>
);
}
export default AlarmClockControl;
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import SayHi from './SayHi';
import AlarmClockControl from './AlarmClockControl';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<AlarmClockControl />, document.getElementById('root'));
registerServiceWorker();