开发者问题收集

event.target.value 在 React 中给出 TypeError

2020-04-18
62

这是我使用 React hooks 的功能组件中的代码:

const Form = () => {
  const [title, setTitle] = useState("");
  const handleSubmit = (e) => {
    e.preventDefault();
  };
  const handleChange = (e) => {
    setTitle((currentTitle) => {
      console.log(e.target.value);
    });
  };
  return (
    <form onSubmit={handleSubmit}>
      <input type="text" value={title} onChange={handleChange} />
      <input type="submit" value="Submit" />
    </form>
  );
};

因此, console.log(e.target.value) 在这里给了我 TypeError: Cannot read property 'value' of null 。为什么?

但是我尝试这样做:

const handleChange = (e) => {
    const newTitle = e.target.value;
    setTitle((currentTitle) => {
      console.log(newTitle);
    });
  };

并且这按预期工作,但是为什么呢?

1个回答

React 使用名为 合成事件 的自定义事件来代替原生事件。这是为了提高性能和事件池化。来自 文档

The SyntheticEvent is pooled. This means that the SyntheticEvent object will be reused and all properties will be nullified after the event callback has been invoked. This is for performance reasons. As such, you cannot access the event in an asynchronous way.

当您在 setState 中使用它时,而该 异步 ,您正在破坏此流程。

相反,合成事件允许您添加一种不重复使用它的方法:

const handleChange = (e) => {
  e.persist();  
  setTitle((currentTitle) => {
    console.log(e.target.value);
  });
};

If you want to access the event properties in an asynchronous way, you should call event.persist() on the event, which will remove the synthetic event from the pool and allow references to the event to be retained by user code.

或者您可以在将事件传递给异步函数之前访问它。

const handleChange = (e) => {
  const newTitle = e.target.value;
  setTitle((currentTitle) => {
    console.log(newTitle);
  });
};
Agney
2020-04-18