我用 useState 初始化了这个对象:
const [
emailNotifications,
setEmailNotifications,
] = useState<emailNotifications>({
rating: false,
favourites: false,
payments: false,
refunds: false,
sales: false,
});
我创建了一个函数,该函数应动态更改每个字段的值,但我正在努力为 onClick 分配相反的 bool 值。这是函数:
const handleEmailNotificationsSettings = (
event: React.ChangeEvent<HTMLInputElement>
) => {
setEmailNotifications({
...emailNotifications,
[event.target.id]: !event.target.id,
});
};
我做错了什么?
最佳答案
您的方法是正确的,只是您尝试在此处实现的一个小问题是错误的。
setEmailNotifications({
...emailNotifications,
[event.target.id]: !event.target.id, //Here
});
当您将动态值设置为您期望的状态时,它不是 bool 值
解决方法:
setEmailNotifications({
...emailNotifications,
[event.target.id]: !emailNotifications[event.target.id],
});
https://stackoverflow.com/questions/66761826/
相关文章:
django - 如何从 drf-spectacular API 文档中删除 RetrieveUpd
javascript - 不要将数字或单词替换为下划线,而是保留破折号并删除其周围的空格
go - Helm : How to convert a string into lower/upp
regex - 查找以 RegEx 结尾的字符串替换失败?谷歌脚本
haskell - 合并两个 Either Monad 的结果
javascript - Material-UI Select 在 onChange 后不更新