我得到了一个具有不同颜色背景的列表3 div,如果我单击其中一个,该函数将状态设置为true,它将呈现嵌套在div内的刻度图标,但我只能选择一种颜色,如何修改代码,因此如果我单击一个div,该div的状态将为true,并且该div图标将出现,但它将从其他div中消失(如果以前选择了)。

const [colorPick, setColorPick] = useState(false);
const colorPickHandler = () => {
setColorPick(!colorPick);
};
<button className="cursor-pointer" onClick={colorPickHandler}>
<div className="mt-3 border-2 border-solid border-black bg-red-600 w-8 h-8">
{colorPick && (
<svg
xmlns="http://www.w3.org/2000/svg"
className="h-6 w-6"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
stroke-width="2"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M5 13l4 4L19 7"
/>
</svg>
)}
</div>
</button>
<button className="cursor-pointer" onClick={colorPickHandler}>
<div className="mt-3 border-2 border-solid border-black bg-blue-600 w-8 h-8">
{colorPick && (
<svg
xmlns="http://www.w3.org/2000/svg"
className="h-6 w-6"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
stroke-width="2"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M5 13l4 4L19 7"
/>
</svg>
)}
</div>
</button>
<button className="cursor-pointer" onClick={colorPickHandler}>
<div className="mt-3 border-2 border-solid border-black bg-pink-600 w-8 h-8">
{colorPick && (
<svg
xmlns="http://www.w3.org/2000/svg"
className="h-6 w-6"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
stroke-width="2"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M5 13l4 4L19 7"
/>
</svg>
)}
</div>
</button>发布于 2022-05-23 07:22:01
colourPick应该是字符串,而不是布尔值。
它应该具有“红色”、“蓝色”或“棕色”的价值。
所以您可以做一些类似colourPick ===“red”&& renderSvg之类的事情。
发布于 2022-05-23 11:45:04
您可以像对象一样为所有3种颜色定义状态。喜欢,
state = {red:false, blue:false, yellow:false};if (e.target.name === 'red') setState = { red:true, blue:false, yellow:false }
else if (e.target.name === 'blue') setState = { red:false, blue:true, yellow:false };
else if (e.target.name === 'yellow') setState = { red:false, blue:false, yellow:true }这里的
需要在ColorPicker(e)函数中传递
e参数。
并将name="red"添加到红色按钮中,并分别用于其他按钮。
https://stackoverflow.com/questions/72343884
复制相似问题