React.js中使用数组与useState实现按钮单独变色问题
解决单个按钮点击仅改变自身颜色的问题
你当前的问题是所有按钮共用了同一个状态变量clsitemchanged,所以点击任意按钮时,所有按钮的类名都会同步更新。要实现单个按钮独立变色,需要调整状态来记录选中的按钮ID,而非统一的类名字符串。
修改步骤:
- 将状态从存储类名字符串改为存储选中的按钮ID,初始值可以设为
null(表示没有选中任何按钮) - 渲染每个按钮时,通过对比当前按钮的ID和选中ID,动态决定使用哪个类名
- 点击按钮时,更新选中ID为当前按钮的ID(如果已经选中则取消,可选逻辑)
修改后的完整代码:
export default function CategoryPicker() { const categorylist = [ { label: "Fact", id: 0 }, { label: "Event", id: 1 }, { label: "People", id: 2 }, { label: "Secure", id: 3 }, ]; // 状态改为记录选中的按钮ID,初始无选中 const [selectedId, setSelectedId] = useState(null); return ( <div> Select a category <style>{` .blue { color: rgb(59,130,246); border: 2px solid rgb(59,130,246); background-color:white; padding:12px 15px; inline-size:80px; border-radius: 9999px; margin-inline-start:3px; } .white { color: white; border: 2px solid rgb(59,130,246); background-color:rgb(59,130,246); padding:12px 15px; inline-size:80px; border-radius: 9999px; margin-inline-start:3px; } `}</style> {categorylist.map((currentElement) => { return ( <button // 根据当前按钮ID是否等于选中ID,动态切换类名 className={selectedId === currentElement.id ? "white" : "blue"} key={currentElement.id} // 点击时切换选中状态:如果已选中则取消,否则设置为当前ID onClick={() => setSelectedId(prev => prev === currentElement.id ? null : currentElement.id) } > {currentElement.label} </button> ); })} </div> ); }
额外说明:
如果需要实现「单选」(始终只有一个按钮处于选中状态),可以把点击事件简化为onClick={() => setSelectedId(currentElement.id)},这样点击新按钮时会直接替换选中ID,无需取消逻辑。
内容的提问来源于stack exchange,提问作者Lili
相关产品推荐
相关产品推荐

