这是我得到的错误在这里它是显示我的错误,变量没有定义我怎么能修复这是有任何方法,我可以使用?
const [indication, setindication] = React.useState({
venous: "",
flutter: "",
heartValve: "",
peripheral: "",
antibody: "",
other: "",
});
const handleChange = (event) => {
const { name: key, value } = event.target;
if (key === venous) setindication({ ...indication, venous: value });
else if (key === flutter) setindication({ ...indication, flutter: value });
else if (key === heartValve)
setindication({ ...indication, heartValve: value });
else if (key === peripheral)
setindication({ ...indication, peripheral: value });
else if (key === antibody)
setindication({ ...indication, antibody: value });
else if (key === other) setindication({ ...indication, other: value });
else setindication({ ...indication, [key]:"" });
};
这里这是我使用的条件类型,我想在我的复选框中应用它,如果有人能帮助我这个问题将是非常有帮助的。
<FormGroup>
<FormControlLabel
value={indication.venous}
name="venous"
onChange={handleChange}
control={
<Checkbox />
}
label={
<Typography fontSize={20}>
Venous Thromboembolism (VTE)
</Typography>
}
labelPlacement="start"
/>
</FormGroup>
更新
仍然不确定我是否完全理解所需的结果,但如果首选的indication
状态是一个选定值的数组,如["venous"]
,["venous", "other"]
等,这里是一个可能的例子。
简化的实时演示:stackblitz
将状态定义为[]
数组并修改事件处理程序以填充该数组:
const [indication, setindication] = React.useState([]);
const handleChange = (event) =>
setindication((prev) =>
prev.includes(event.target.name)
? prev.filter((item) => item !== event.target.name)
: [...prev, event.target.name]
);
因为indication
现在是一个仅用于选择值的数组,所以选项的数据需要保存在另一个const
中,或者它可以来自props:
const optionsData = {
venous: "",
flutter: "",
heartValve: "",
peripheral: "",
antibody: "",
other: "",
};
原来
由于FormControlLabel
的value
与indication.venous
绑定,因此无论是否检查Checkbox
,它似乎总是""
空字符串。
假设这个组件看起来像Checkbox
,也许预期的结果是保存哪些选项被选中(true
或false
)?
如果是这样,也许事件处理程序可以将event.target.checked
设置为新值,例如:
const handleChange = (event) =>
setindication((prev) => ({
...prev,
[event.target.name]: event.target.checked,
}));
一个快速的演示,希望可以帮助您可视化:
变量key
看起来应该是字符串。试试这个:
const handleChange = (event) => {
const { name: key, value } = event.target;
if (key === "venous") setindication({ ...indication, venous: value });
else if (key === "flutter") setindication({ ...indication, flutter: value });
else if (key === "heartValve")
setindication({ ...indication, heartValve: value });
else if (key === "peripheral")
setindication({ ...indication, peripheral: value });
else if (key === "antibody")
setindication({ ...indication, antibody: value });
else if (key === "other") setindication({ ...indication, other: value });
else setindication({ ...indication, [key]:"" });
};