英文:
Why can't I use '!checked' to toggle the checked property of my checkbox in React?
问题
我有一些组件中的状态,用来保存复选框元素的值。我需要在复选框被点击时更新状态和用户界面。我的问题是为什么我不能像这样使用!checked
:
function handleChange(event) {
const { name, value, type, checked } = event.target;
console.log(checked);
setFormData((prevState) => {
return {
...prevState,
[name]: type === "checkbox" ? !checked : value,
};
});
console.log(checked);
}
这种方式不能更新状态或用户界面。相反,我必须将它更改为checked
才能看到UI/状态更新。根据我的理解,checked
属性来自目标事件。也就是这个复选框:
<input
id="okayToEmail"
type="checkbox"
checked={formData.hasJoined}
name="hasJoined"
onChange={handleChange}
/>
checked
属性或属性值来自此处的状态:
const [formData, setFormData] = React.useState({
email: "",
password: "",
confirmedPassword: "",
hasJoined: true,
});
你可以看到checked
属性等于一个布尔值。那么为什么我不能使用!checked
?当我给它checked
的原始值时,用户界面是如何来回切换的?这让我感到困惑。你能用通俗的话解释一下吗?谢谢!
英文:
I have some state in my component that holds the value of my checkbox element. I need to update the state as well as the UI everytime the checkbox is clicked. My Question is why I can't use !clicked
like this
function handleChange(event) {
const {name, value, type, checked} = event.target
console.log(checked)
setFormData(prevState => {
return {
...prevState,
[name]: type === "checkbox" ? !checked : value
}
})
console.log(checked)
}
this doesn't work in updating the state or the UI. Instead I have to change it to checked
to see the UI/State update. From my understanding the checked
property comes from the targeted event
. Which is this checkbox.
<input
id="okayToEmail"
type="checkbox"
checked={formData.hasJoined}
name="hasJoined"
onChange={handleChange}
/>
the value for the checked
property or attribute comes from the state here.
const [formData, setFormData] = React.useState({
email: "",
password: "",
confirmedPassword: "",
hasJoined: true
})
you can see the checked
property equates to a boolean. So why can't I use !checked
?? How is the UI toggling back and forth when I'm giving it the original value of checked
?? This hurts my brain. Can you please explain this in lamen terms. Thank you!
答案1
得分: 1
event.target.checked
是最新的复选框数值,您不需要对其取反,这应该可以工作:
return {
...prevState,
[name]: type === "checkbox" ? checked : value,
};
或者您可以从prevState
中取反:
return {
...prevState,
[name]: type === "checkbox" ? !prevState.hasJoined : value,
};
英文:
event.target.checked
is the latest checkbox value, you don't need to negate that, this should work:
return {
...prevState,
[name]: type === "checkbox" ? checked : value,
};
or you can negate from the prevState
:
return {
...prevState,
[name]: type === "checkbox" ? !prevState.hasJoined : value,
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论