我得到了一個具有不同顏色背景的 3 個 div 串列,如果我單擊其中一個,該函式會將 State 設定為 true,這將呈現嵌套在 div 內的刻度圖示,但我只能選擇一種顏色,如何我可以修改代碼,因此如果我單擊一個 div,則該 div 的狀態將為 true,并且會出現勾號圖示,但它會從另一個 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>
uj5u.com熱心網友回復:
colourPick 應該是一個字串,而不是一個布林值
它應該采用“紅色”、“藍色”或“棕色”的值
所以你可以做像 colourPick === “red” && renderSvg
uj5u.com熱心網友回復:
您可以將狀態定義為所有 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 }
這里您需要
e在 ColorPicker(e) 函式中傳遞引數。
并分別添加 name="red"到紅色按鈕和其他人。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/480768.html
