我有一個技術面試。我的代碼按照說明作業,但我想知道如何通過使用 Id 并使用單個函式而不是三個函式來優化它。
以下是交通燈指示:
如果一個圓圈是白色的,當點擊該圓圈時,它應該以適當的顏色點亮。(頂部 = 紅色,中間 = 黃色,底部 = 綠色)
如果一個圓圈已經亮起,再次單擊時,它應該會變回白色。
一次只能點亮一盞燈。如果一盞燈已經亮起,而您單擊另一個白色圓圈,則先前亮起的燈應熄滅,單擊的燈應變為適當的顏色。
我要優化的代碼:
我目前有 3 個功能,我想將其濃縮為一個。
toggleRedtoggleYellow和toggleGreen。每個代碼塊幾乎相同。我還想知道是否有更好的方法來使用狀態來跟蹤打開的燈。目前,我有 3 個不同的 useStates 來跟蹤每種顏色。我覺得我有更好的方法來處理這個問題。
我的作業代碼:
import "./styles.css";
import React, { useState } from "react";
export default function App() {
const [litRed, setLitRed] = useState("white");
const [litYellow, setLitYellow] = useState("white");
const [litGreen, setLitGreen] = useState("white");
const toggleRed = (e) => {
if (litRed == "white") {
setLitRed("red");
setLitYellow("white");
setLitGreen("white");
} else {
setLitRed("white");
setLitYellow("white");
setLitGreen("white");
}
};
//setLitYellow("yellow")
const toggleYellow = (e) => {
};
//setLitGreen("green")
const toggleGreen = (e) => {
};
return (
<div className="App">
<div id="traffic-light">
<button
id="top"
style={{ backgroundColor: litRed }}
onClick={toggleRed}
/>
<button
id="middle"
style={{ backgroundColor: litYellow }}
onClick={toggleYellow}
/>
<button
id="bottom"
style={{ backgroundColor: litGreen }}
onClick={toggleGreen}
/>
</div>
</div>
);
}
uj5u.com熱心網友回復:
我認為您可以使用狀態來存盤當前點亮的燈光的索引,而不是使用 3 狀態。
import "./styles.css";
import React, { useState } from "react";
export default function App() {
const [litPos, setLitPos] = useState(-1);
return (
<div className="App">
<div id="traffic-light">
<button
id="top"
style={{ backgroundColor: litPos === 0 ? 'red' : 'white' }}
onClick={() => setLitPos(litPos === 0 ? -1 : 0)}
/>
<button
id="middle"
style={{ backgroundColor: litPos === 1 ? 'yellow' : 'white' }}
onClick={() => setLitPos(litPos === 1 ? -1 : 1)}
/>
<button
id="bottom"
style={{ backgroundColor: litPos === 2 ? 'green' : 'white' }}
onClick={() => setLitPos(litPos === 2 ? -1 : 2)}
/>
</div>
</div>
);
}
useState(-1)表示還沒有亮燈。將litPos用來指示哪個指示燈點亮。0代表紅色,1代表黃色,2代表綠色。
如果您單擊紅燈 (pos 0),它將檢查當前listPos.
litPos === 0 ? -1 : 0
如果當前 litPos 為 0,則表示右側的燈亮了,因此我們需要將其設定回 -1 將其關閉,否則,我們將其設定為 0 將其打開。它也適用于其他燈。
對于背景顏色,我們只需要根據當前的 改變背景顏色,即現在litPos哪個燈亮著。
backgroundColor: litPos === 0 ? 'red' : 'white'
uj5u.com熱心網友回復:
我會在 onClick 中使用匿名函式并將顏色作為字串傳遞給函式。
<button
id="top"
style={{ backgroundColor: litRed }}
onClick={()=>toggle("red")}
/>
然后你可以稍微簡化切換功能,看起來像這樣:
const toggle = (color) => {
if(color === "red"){
if (litRed == "white") {
setLitRed("red");
} else {
setLitRed("white");
}
setLitYellow("white");
setLitGreen("white");
}
//Code for yellow and red
};
此外,為了代碼清晰,您可以在 const 物件中放置“白色”、“紅色”、“黃色”和“綠色”,類似于其他語言中的列舉。
const Direction = {
WHITE: 'WHITE',
... };
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/354924.html
標籤:javascript 反应 使用状态
上一篇:第一個完整頁面來啦~小米官網
下一篇:React函式被多次呼叫(每秒)
