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

React JS中实现按钮单选点击变色(切换恢复原色)方案求助

最优实现方案:单状态管理选中按钮

你的需求是实现单选按钮组(点击一个按钮变红,其他恢复白色),不需要维护整个背景色数组,用单个状态记录当前选中的索引是更简洁高效的方案,具体修改如下:

1. 替换背景色状态

删掉原来的bgcolor状态,改用单个状态变量记录选中索引:

import { useState } from 'react';
// ...
const [selectedIndex, setSelectedIndex] = useState(0); // 默认选中第一个"All"按钮,若初始无选中可设为-1

2. 修改按钮渲染逻辑

直接在按钮的sx属性中根据selectedIndex判断背景色:

{priceranges.map((range, index) => (
  <Button
    key={index}
    sx={{
      backgroundColor: selectedIndex === index ? "red" : "white",
      border: "1px solid pink",
      height: "30px",
      margin: "5px 5px 0 5px",
      fontSize: {
        xs: "0.6em",
        sm: "0.8em",
        md: "0.9em",
        lg: "0.9em",
        xl: "0.9em",
      },
    }}
    onClick={() => filterproducts(range, index)}
  >
    {range.displayas}
  </Button>
))}

3. 完善点击函数逻辑

点击时更新选中索引,同时保留你的产品过滤逻辑:

const filterproducts = (range, index) => {
  setSelectedIndex(index);
  // 这里添加你的产品过滤逻辑,比如:
  // filterProductsByPriceRange(range.range);
};

为什么原来的思路有问题?

你之前用new Array(priceranges.length).fill({ color: "white" })创建的数组,所有元素都引用同一个对象,修改其中一个元素的color时,会导致所有按钮的背景色同时变化,这是因为fill方法对于引用类型是浅拷贝。而且维护整个数组的状态,比维护单个索引要繁琐得多,性能也更差。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 01:20:38