React 复选框无法重置为默认未选中状态
React checkbox cannot reset to default unchecked state
我正在尝试重现 Youtuber Traversy Media 的 React JS crash course 2021 Task Tracker project with Reactstrap, and using the same method(a component level hook) to create a form with a checkbox in it, and I set up a method, make sure after the form submitted, the text area will be set to empty and the checkbox set to false, and therefore unchecked. When I hit submit, the checkbox had set to false, but remain checked. 从 React 开发工具中,该值被重置为 false 并且应该取消选中该复选框,我不知道出了什么问题,我做了确切的和视频做的一样。我在此处粘贴代码时遇到问题,因此省略了不相关的部分,例如输入文本代码。提前致谢!
const [reminder, setReminder] = useState(false);
const onSubmit = (e) => {
e.preventDefault()
if (!text) {
alert('Please add a task')
return
}
onAdd({ text, day, reminder })
setText('')
setDay('')
setReminder(false)}
{/* checkbox here */}
<div className="mb-3 form-check">
<input
type="checkbox"
id="checkbox1"
className="form-check-input"
value={reminder}
onChange={(e) => setReminder(e.currentTarget.checked)}
/>
<label className="form-check-label" htmlFor="checkbox1">
Set reminder
</label>
</div>
{/* submit button */}
<div className="d-grid">
<button type="submit" className="btn btn-primary">
Submit
</button>
</div>
这样做会奏效:
<input
type="checkbox"
id="checkbox1"
className="form-check-input"
checked={reminder}
onChange={(e) => setReminder(e.currentTarget.checked)}
/>
我正在尝试重现 Youtuber Traversy Media 的 React JS crash course 2021 Task Tracker project with Reactstrap, and using the same method(a component level hook) to create a form with a checkbox in it, and I set up a method, make sure after the form submitted, the text area will be set to empty and the checkbox set to false, and therefore unchecked. When I hit submit, the checkbox had set to false, but remain checked.
const [reminder, setReminder] = useState(false);
const onSubmit = (e) => {
e.preventDefault()
if (!text) {
alert('Please add a task')
return
}
onAdd({ text, day, reminder })
setText('')
setDay('')
setReminder(false)}
{/* checkbox here */}
<div className="mb-3 form-check">
<input
type="checkbox"
id="checkbox1"
className="form-check-input"
value={reminder}
onChange={(e) => setReminder(e.currentTarget.checked)}
/>
<label className="form-check-label" htmlFor="checkbox1">
Set reminder
</label>
</div>
{/* submit button */}
<div className="d-grid">
<button type="submit" className="btn btn-primary">
Submit
</button>
</div>
这样做会奏效:
<input
type="checkbox"
id="checkbox1"
className="form-check-input"
checked={reminder}
onChange={(e) => setReminder(e.currentTarget.checked)}
/>