Javascript event.target.value在React中给出TypeError
下面是我使用React钩子的功能组件中的代码:Javascript event.target.value在React中给出TypeError,javascript,reactjs,Javascript,Reactjs,下面是我使用React钩子的功能组件中的代码: const Form = () => { const [title, setTitle] = useState(""); const handleSubmit = (e) => { e.preventDefault(); }; const handleChange = (e) => { setTitle((currentTitle) => { console.log(e.targe
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>
);
};
这正如预期的那样工作,但为什么?React使用名为的自定义事件而不是本机事件。这是为了性能和事件池。从: 该事件是合并的。这意味着将重用SyntheticEvent对象,并且在调用事件回调后,所有属性都将为空。这是出于性能原因。因此,您不能以异步方式访问事件 当您在
setState
内部使用它时,它本身就是,您正在破坏这个流
相反,合成事件允许您添加一个不重用它的方法:
const handleChange = (e) => {
e.persist();
setTitle((currentTitle) => {
console.log(e.target.value);
});
};
如果希望以异步方式访问事件属性,则应该对事件调用event.persist(),这将从池中删除合成事件,并允许用户代码保留对事件的引用
或者,您可以在将事件传递给异步函数之前访问该事件
const handleChange = (e) => {
const newTitle = e.target.value;
setTitle((currentTitle) => {
console.log(newTitle);
});
};
const handleChange = (e) => {
const newTitle = e.target.value;
setTitle((currentTitle) => {
console.log(newTitle);
});
};