红绿灯问题。点击切换颜色

traffic light problem. Toggling colors on click

我进行了一次技术面试。我的代码按照说明工作,但我想知道如何通过使用 Id 和使用单个函数而不是三个来优化它。

下面是红绿灯说明:

我要优化的代码:


我的工作代码:

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>
  );
}

我想你可以用一个状态来存储当前点亮的灯的索引,而不是使用 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'

我会在 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
  };

此外,为了代码清晰,您可以将“white”、“red”、“yellow”和“green”放在 const 对象中,类似于其他语言中的枚举。

const Direction = {
  WHITE: 'WHITE',

... };