我接受了一次技术面试。我的代码按照说明工作,但我想知道如何通过使用Id和使用一个函数而不是三个函数来优化它。
下面是一个红绿灯说明:
我想优化的代码:
toggleRed toggleYellow和toggleGreen.每个代码块几乎是相同的。,
我的工作代码:
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>
);
}发布于 2021-11-10 04:58:24
我认为您可以使用状态来存储当前照明光的索引,而不是使用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'
发布于 2021-11-10 05:05:07
我将在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://stackoverflow.com/questions/69907997
复制相似问题