在React裡要如何控制元件的顯示呢? 例如,我們希望能讓學生能依次完成數學加法題、減法題、及加減法混合題,在React裡要如何處理呢? 我們可以很容易的讓這些題目同時出現,但是,要如何變成依次出現呢?
新增Exam.js
import "./styles.css";
import Add from "./Add";
import Chemistry from "./Chemistry";
import ChemistryMultiple from "./ChemistryMultiple";
import ChemistryRadio from "./ChemistryRadio";
export default function Exam() {
return (
<div className="App">
**<Add />
<Chemistry />
<ChemistryMultiple />
<ChemistryRadio />**
</div>
);
}
App.js內容改為:
import "./styles.css";
import Exam from "./Exam";
export default function App() {
return (
<div className="App">
<h1>測驗</h1>
<h2>線上測驗</h2>
**<Exam />**
</div>
);
}
元件之間就形成了Parent與Child的關係了,App是Exam的Parent元件,Exam是Add、Chemistry等元件的Parent元件。反過來,Exam是App的Child元件,Add、Chemistry等元件是Exam的Child元件。
我們來加個下拉式選單:
import "./styles.css";
import Add from "./Add";
import Chemistry from "./Chemistry";
import ChemistryMultiple from "./ChemistryMultiple";
import ChemistryRadio from "./ChemistryRadio";
export default function Exam() {
return (
<div className="App">
**<select>
<option value="0">數學</option>
<option value="1">化學符號填空題</option>
<option value="2">化學符號選擇題</option>
<option value="3">化學元素家族</option>
</select>**
<Add />
<Chemistry />
<ChemistryMultiple />
<ChemistryRadio />
</div>
);
}
跟radio按鈕很像,當選項更動時,更動state變數(currentExam)
import "./styles.css";
import Add from "./Add";
import Chemistry from "./Chemistry";
import ChemistryMultiple from "./ChemistryMultiple";
import ChemistryRadio from "./ChemistryRadio";
export default function Exam() {
**const [currentExam, setCurrentExam] = useState(0);
function onChangeExam(event) {
setCurrentExam(Number(event.target.value));
}**
return (
<div className="App">
<select **onChange={onChangeExam}**>
<option value="0">數學</option>
<option value="1">化學符號填空題</option>
<option value="2">化學符號選擇題</option>
<option value="3">化學元素家族</option>
</select>
<Add />
<Chemistry />
<ChemistryMultiple />
<ChemistryRadio />
</div>
);
}
接下來就是根據currentExam的值,決定要回傳哪個元件:
import "./styles.css";
import Add from "./Add";
import Chemistry from "./Chemistry";
import ChemistryMultiple from "./ChemistryMultiple";
import ChemistryRadio from "./ChemistryRadio";
import { useState } from "react";
export default function Exam() {
const [currentExam, setCurrentExam] = useState(0);
function onChangeExam(event) {
setCurrentExam(Number(event.target.value));
}
**function getCurrentExam() {
switch (currentExam) {
case 0:
return <Add />;
case 1:
return <Chemistry />;
case 2:
return <ChemistryRadio />;
default:
return <ChemistryMultiple />;
}
}**
return (
<div className="App">
<select name="exam" value={currentExam} onChange={onChangeExam}>
<option value={0}>數學</option>
<option value={1}>化學符號填空題</option>
<option value={2}>化學符號選擇題</option>
<option value={3}>化學元素家族</option>
</select>
**{getCurrentExam()}**
</div>
);
}
<aside> 💡 可以利用props讓Child元件(如:Add)接受變數,但是,為了避免side effect,Child元件是無法更動傳進來的變數。不過,可以利用props讓Child元件接受函數,透過這樣去變更Parent元件(Exam.js)的變數。
</aside>