简体   繁体   English

event.target.value 在 React 中给出 TypeError

[英]event.target.value is giving TypeError in React

Here's the code in my functional component where I'm using React hooks:这是我使用 React 钩子的功能组件中的代码:

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>
  );
};

So the console.log(e.target.value) is giving me TypeError: Cannot read property 'value' of null here.所以console.log(e.target.value)给我TypeError: Cannot read property 'value' of null here。 Why?为什么?

But then I tried doing it like this:但后来我尝试这样做:

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

And this worked as expected, but why?这按预期工作,但为什么呢?

React uses a custom event named Synthentic event instead of the native event. React 使用名为Synthentic 事件的自定义事件而不是原生事件。 This is for performance and pooling of events.这是为了性能和事件池。 From the docs :文档

The SyntheticEvent is pooled. SyntheticEvent 是池化的。 This means that the SyntheticEvent object will be reused and all properties will be nullified after the event callback has been invoked.这意味着 SyntheticEvent object 将被重用,并且在调用事件回调后所有属性都将无效。 This is for performance reasons.这是出于性能原因。 As such, you cannot access the event in an asynchronous way.因此,您不能以异步方式访问事件。

When you are using it inside a setState which itself is asynchronous , you are breaking this flow.当您在本身是异步setState中使用它时,您正在打破这个流程。

Instead, the synthetic event allows you to add a method for not reusing it:相反,合成事件允许您添加不重用它的方法:

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.如果您想以异步方式访问事件属性,您应该在事件上调用 event.persist(),这将从池中删除合成事件并允许用户代码保留对事件的引用。

Or you could access the event before it is passed to the async function.或者您可以在将事件传递给异步 function 之前访问该事件。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM