You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React红绿灯交互代码优化:合并重复函数与简化状态管理方案

优化实现方案

核心优化点

  • 状态管理优化:删除3个独立的useState,仅用1个状态记录当前点亮的灯ID,未点亮时值为null,减少冗余状态
  • 函数合并:仅保留1个通用切换函数,通过事件对象获取点击元素的ID完成逻辑判断,无需重复编写多份功能近似的函数

完整优化后代码

import "./styles.css";
import React, { useState } from "react";

// 建立ID和对应灯色的映射关系,方便后续扩展修改
const LIGHT_COLOR_MAP = {
  top: "red",
  middle: "yellow",
  bottom: "green"
};

export default function App() {
  // activeLight存当前点亮的灯ID,null代表全灭
  const [activeLight, setActiveLight] = useState(null);

  const toggleLight = (e) => {
    const clickedId = e.target.id;
    // 如果点击的是已经点亮的灯,直接熄灭所有
    if (clickedId === activeLight) {
      setActiveLight(null);
    } else {
      // 否则切换为点击的灯点亮,其余自动熄灭
      setActiveLight(clickedId);
    }
  };

  return (
    <div className="App">
      <div id="traffic-light">
        <button
          id="top"
          style={{ backgroundColor: activeLight === "top" ? LIGHT_COLOR_MAP.top : "white" }}
          onClick={toggleLight}
        />
        <button
          id="middle"
          style={{ backgroundColor: activeLight === "middle" ? LIGHT_COLOR_MAP.middle : "white" }}
          onClick={toggleLight}
        />
        <button
          id="bottom"
          style={{ backgroundColor: activeLight === "bottom" ? LIGHT_COLOR_MAP.bottom : "white" }}
          onClick={toggleLight}
        />
      </div>
    </div>
  );
}

逻辑符合说明

完全匹配要求的交互规则:

  • 点击白色按钮时,对应颜色灯点亮,其余灯自动熄灭,同一时间仅亮一盏
  • 点击已点亮的按钮时,所有灯变回白色
  • 后续如果要增加灯的数量,仅需要修改LIGHT_COLOR_MAP映射和新增对应按钮即可,不用修改核心逻辑,扩展性更好

内容的提问来源于stack exchange,提问作者jgrewal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 14:36:03