当有多个按钮使用相同的功能时,使用单击处理程序可以更改按钮的颜色



我有三个按钮使用相同的点击处理程序。-我的愿望是点击时只更改一个按钮的颜色。

如果单击另一个按钮,我希望之前单击的按钮返回到"蓝色"(原始状态(。

下面的示例代码:

import React, { useState } from 'react';
export default function App() {
const [state, setState] = useState({
name: 'bob',
color: 'blue',
});
const handleColor = (e) => {
setState((state) => ({
...state,
color: 'red',
}));
};

return (
<div>
<button style={{ backgroundColor: state.color }} onClick={handleColor}>Click Me</button>
<button style={{ backgroundColor: state.color }} onClick={handleColor}>Click Me 2</button>
<button style={{ backgroundColor: state.color }} onClick={handleColor}>Click Me 3</button>
</div>
);
}

你看起来像这个吗

const lists = [
{ id: 1, title: "Click 1" },
{ id: 2, title: "Click 2" },
{ id: 3, title: "Click 3" }
];
export default function App() {
const [selected, setSelected] = useState(0);
const [state, setState] = useState({
name: "bob",
color: "blue"
});
const handleColor = (row) => {
setSelected(row.id);
};
return (
<div>
{lists.map((list) => (
<button
key={list.id}
onClick={() => handleColor(list)}
style={{ backgroundColor: list.id === selected ? "red" : "" }}
>
{list.title}
</button>
))}
</div>
);
}

实时工作演示

如果您一次只想激活一个按钮,请跟踪哪个按钮是激活的,而不是它是什么颜色。

// hypothetical list of buttons. these could be objects with labels, etc.
// but for the purposes of this example they're just empty slots.
const buttons = Array(3);
// the index of the currently active button
const [active, setActive] = useState();
return (
<div>
{ buttons.map((button, index) => ( // render a button for each item in the array
<button
style={active === index ? { backgroundColor: 'red' } : {}}
onClick={() => setActive(index)}>
Click Me
</button>
)}
</div>
)

您必须为每个按钮维护单独的状态。你可以做一些类似的事情

import React, { useState } from 'react';
export default function Parent() {
const initialButtonState = {
color1: 'blue',
color2: 'blue',
color3: 'blue',
} 

const [state, setState] = useState({...initialButtonState , name: 'bob'});
const handleColor = (colorName) => {
setState((state) => ({
...state,
...initialButtonState ,
[colorName] : 'red'
}));
};

return (
<div>
<button style={{ backgroundColor: color1 }} onClick={ () => handleColor("color1))}>Click Me</button>
<button style={{ backgroundColor: color2 }} onClick={() => handleColor("color2")}>Click Me 2</button>
<button style={{ backgroundColor: color3 }} onClick={() => handleColor("color3")}>Click Me 3</button>
</div>
);
}

最新更新