选择按钮场景
react检测状态变化后渲染
import React, { useState } from 'react';
const ButtonList = () => {
const [buttons, setButtons] = useState([
{ id: 1, selected: false },
{ id: 2, selected: false },
{ id: 3, selected: false },
]);
const handleClick = (id) => {
const newButtons = buttons.map(button => ({
...button, // 复制按钮对象
selected: button.id === id // 根据条件设置selected值
}));
setButtons(newButtons); // 更新状态
};
return (
<div>
{buttons.map(button => (
<button
key={button.id}
style={{ backgroundColor: button.selected ? 'blue' : 'gray' }}
onClick={() => handleClick(button.id)}
>
Button {button.id}
</button>
))}
</div>
);
};
export default ButtonList;