javascript - 在 reactjs 的 onChange 字段中访问时,输入字段目标为空

标签 javascript html reactjs

即使我将值分配给名称和值字段,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 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.

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/

相关文章:

javascript - `{where: ' 原始查询'}` 的支持已被删除

javascript - React 组件从一种类型更改为另一种类型

Python Pandas to_html 样式

html - 为什么我的 div 不是 float 的 :right working?

reactjs - 需要帮助理解这种奇怪的 Jest 行为

javascript - 使用Html.BeginForm/Ajax.BeginForm的FileUpload控件不起作用。(IE中拒绝html文件访问)。Css样式上传控件按钮

javascript - 查找与其表 onclick 事件关联的 td

html - IE8 按钮的 CSS "initial"值

javascript - React 在我的组件实际拥有数据之前渲染它

reactjs - React Router 渲染空脚本标签