gpt4 book ai didi

javascript - 无法读取空输入字段的属性 'value'?

转载 作者:行者123 更新时间:2023-11-30 14:24:32 28 4
gpt4 key购买 nike

每当我在 input 字段中输入时,我都会收到以下错误:-

Cannot read property 'value' of null

我有一个表单,其中有一个 input 字段搜索值,当我尝试输入任何内容时出现错误。

Here是我的代码。

关于这个功能的问题

handleInputFieldChange = (event, name) => {
this.setState(preState => ({
...preState,
form: {
...preState.form,
[name]: event.target.value
}
}));
};

最佳答案

React lib 本身有一个警告,它基本上指导你如何解决这个问题。

Warning: This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the property target on a released/nullified synthetic event. This is set to null. If you must keep the original synthetic event around, use event.persist()

因此解决方法是在局部变量中获取目标对象的引用,如下所示。

handleInputFieldChange = (event, name) => {
const { target } = event;
this.setState(preState => ({
...preState,
form: {
...preState.form,
[name]: target.value
}
}));
};

只有当您使用 updater 函数和 setState 方法时才会发生这种情况。他们要求使用 event.persist(),但在我的应用程序中,只需引用 target 对象即可在 update 函数,100% 有效。

查看 Event Pooling 的文档

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.

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.

关于javascript - 无法读取空输入字段的属性 'value'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52163338/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com