REACT中如何修复输入和状态?
具有
const [grade, setGrade] = useState({grade: null,})
const changeHandler = (event) => {if (event.value) {setGrade({ ...grade, [event.name]: event.value })} else {setGrade({ ...grade, [event.target.name]: event.target.value })}}
和输入
<input
type="text"
name="grade"
className="homework-block-main-input"
onClick={changeHandler}
/>
时,当我在输入中打印值时,我有
打印“ 1” 有 ”” 打印“ 12” 有“ 1” 打印“ 123” 有“ 12”
如何解决?
当我在输入中打印值时,我会
打印“ 1” 有 ”” 打印“ 12” 有“ 1” 打印“ 123” 有“ 12”
如何解决?
Have
const [grade, setGrade] = useState({grade: null,})
const changeHandler = (event) => {if (event.value) {setGrade({ ...grade, [event.name]: event.value })} else {setGrade({ ...grade, [event.target.name]: event.target.value })}}
and input
<input
type="text"
name="grade"
className="homework-block-main-input"
onClick={changeHandler}
/>
when i print value in input i have
print "1"
have ""
print "12"
have "1"
print "123"
have "12"
How to fix that?
when i print value in input i have
print "1"
have ""
print "12"
have "1"
print "123"
have "12"
How to fix that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先要指出的是
if (event.value) {}
没有意义,因为 event.value 不存在于 event 中,所以它始终是未定义的,第二件事,你应该使用 onChange 代替onClick 事件通常用在按钮中,第三件事,您应该在 useEffect 中执行 console.log 来正确跟踪状态,代码应如下所示:First thing to point out is that
if (event.value) {}
doesn't make sense because event.value doesn't exists in event so it's always undefined, second thing, you should use onChange instead of onClick, the onClick event is generally used in buttons, third thing, you should do a console.log inside a useEffect to track the state correctly, here how you code should looks like: