我正在根據 API 的回應設定 MUI 開關的狀態。此 API 回應中的Active欄位指示 Switch 是選中還是未選中。
如果 JSON 欄位為1,則檢查該開關,如果該欄位為 ,則取消選中該開關0。當我手動檢查或取消檢查開關時,我想通過更改Activeto1或的值在 JSON 中反映這一點0。
const [checked, setChecked] = useState(true);
const [details, setDetails] = useState(""); //This is where my API response is stored
function ActivityStatusSwitch() {
if (details.Active === 1) {
return (
<FormControlLabel
control={<Switch checked={checked} onChange={handleSwitchChange} />}
label="Active"
labelPlacement="start"
/>
);
} else
return (
<FormControlLabel
control={<Switch checked={checked} onChange={handleSwitchChange} />}
label="Inactive"
labelPlacement="start"
/>
);
}
const handleSwitchChange = (e) => {
setChecked(e.target.checked);
setDetails((prev) => {
return { ...prev, Active: e.target.value };
});
};
這是我的 JSON 的一個簡短示例:
{
"Active": 1
}
uj5u.com熱心網友回復:
我一直發現在這種情況下使用布爾狀態更容易。由于您已經在使用 1 和 0,所以這只是真偽。
因此,如果您的Active欄位為真/假,則可以執行以下操作:
const handleSwitchChange = (e) => {
setChecked(e.target.checked);
setDetails((prev) => {
return { ...prev, Active: !prev.Active };
});
};
如果你真的堅持使用 1 & 0,你仍然可以用一個簡單的條件來實作同樣的事情。
const handleSwitchChange = (e) => {
setChecked(e.target.checked);
setDetails((prev) => {
return { ...prev, Active: mapActiveValue(prev.Active) };
});
};
const mapActiveValue = (val) => {
return val === 0 ? 1 : 0
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/487421.html
標籤:javascript 反应 json 材料-ui
