即使我将值分配给名称和值字段,event.target 也会变为 null。 event.target.value 正在获取值(value),但不是任何其他值(value)。
<input type= "text"
name= {value}
value = {currentValue}
onChange = { (e) => this.onInputChanged(e) }
disabled = { disabled }
/>
onInputChanged = async (e) => {
await this.setState({ currentValue: e.target.value })
console.log('event', e.target); //This is showing null
this.props.onInputChange(e);
}
最佳答案
React 重用合成事件对象,因此您不能在异步上下文中按原样使用它。
来自docs :
The
SyntheticEvent
is pooled. This means that theSyntheticEvent
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.Note:
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()
以在异步上下文中使用对象之前保留该对象。
同步提取值:
onInputChanged = event => {
const value = event.target.value;
(async () => {
await this.setState({ currentValue: value });
this.props.onInputChange(e);
})();
}
在异步上下文中使用它之前持久化事件:
onInputChanged = event => {
event.persist();
(async () => {
await this.setState({ currentValue: e.target.value });
console.log('event', e.target);
this.props.onInputChange(e);
})();
}
关于javascript - 在 reactjs 的 onChange 字段中访问时,输入字段目标为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58059004/