我开始学习React钩子,但是我坚持checkbox
的基本行为。我只是想在点击/更改时切换我的复选框。让我知道我在这里做错了。
代码-
import React from "react";
import "./styles.css";
export default function App() {
const [checked, setChecked] = React.useState(true);
const handleChange = e => {
e.persist();
console.log(e.target.checked);
setChecked({ checked: !e.target.checked });
};
return (
<div className="App">
<div className="container">
<div className="list">
<div className="search">Search</div>
<div className="list">
<ul>
<input
type="checkbox"
checked={checked}
onChange={handleChange}
onClick={handleChange}
/>
</ul>
{JSON.stringify(checked)}
</div>
</div>
</div>
</div>
);
}
答案 0 :(得分:1)
主要问题是您两次触发handleChange
函数。
将您的checked
状态的先前状态用作:
const handleChange = e => {
e.persist();
setChecked(prevState => !prevState);
};
还将onChange
元素中的input
删除为:
<input type="checkbox" checked={checked} onClick={handleChange} />
只需测试此解决方案,就可以正常工作。
答案 1 :(得分:0)
const handleChange = e => {
e.persist();
console.log(e.target.checked);
setChecked({ checked: !e.target.checked });
};
此操作失败,因为您正在将checked
设置为对象,但是使用布尔值初始化了状态
const [checked, setChecked] = React.useState(true);
将其更改为此应该可以
const handleChange = e => {
setChecked(prevValue => !prevValue);
};
答案 2 :(得分:0)
if your trying to just toggle checked or not checked, checkbox default is set you just have to return the checkbox as below, from what i can see your setting checked={checked}
<div className="App">
<div className="container">
<div className="list">
<div className="search">Search</div>
<div className="list">
<ul>
<input
type="checkbox"
/>
</ul>
{JSON.stringify(checked)}
</div>
</div>
</div>
</div>
or you could also do the following what i do sometimes, if im doing anything wrong i would love to be corrected.
const handleChange = e => {
setChecked(!checked);
};
<input
type="checkbox"
onChange={handleChange}
/>
答案 3 :(得分:0)
您可以做的另一件事是在句柄检查中添加以下内容
4.9102919