REACT中如何修复输入和状态?

发布于 2025-01-17 08:44:38 字数 661 浏览 0 评论 0原文

具有

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

回忆躺在深渊里 2025-01-24 08:44:38

首先要指出的是 if (event.value) {} 没有意义,因为 event.value 不存在于 event 中,所以它始终是未定义的,第二件事,你应该使用 onChange 代替onClick 事件通常用在按钮中,第三件事,您应该在 useEffect 中执行 console.log 来正确跟踪状态,代码应如下所示:

  const [grade, setGrade] = useState({ grade: '' });

  const changeHandler = (event) => {
    setGrade({ grade: event.target.value });
  };

  useEffect(() => {
    console.log(grade)
  }, [grade]);  

  return (
    <input
      type="text"
      name="grade"
      className="homework-block-main-input"
      onChange={changeHandler}
    ></input>
  );
};

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:

  const [grade, setGrade] = useState({ grade: '' });

  const changeHandler = (event) => {
    setGrade({ grade: event.target.value });
  };

  useEffect(() => {
    console.log(grade)
  }, [grade]);  

  return (
    <input
      type="text"
      name="grade"
      className="homework-block-main-input"
      onChange={changeHandler}
    ></input>
  );
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文