最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - input field target is null while accessing in onChange field in reactjs - Stack Overflow

programmeradmin4浏览0评论

Even if I am assigning value to name and value fields, event.target is getting as null. event.target.value is getting value but not any other.

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

Even if I am assigning value to name and value fields, event.target is getting as null. event.target.value is getting value but not any other.

    <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);
    }
Share Improve this question edited Sep 23, 2019 at 9:06 Shraddha J asked Sep 23, 2019 at 9:02 Shraddha JShraddha J 78411 silver badges18 bronze badges 2
  • You'll need to post some code – Will Jenkins Commented Sep 23, 2019 at 9:04
  • you need to set the value to get value share some of your codebase where you are struggling – ANIK ISLAM SHOJIB Commented Sep 23, 2019 at 9:05
Add a ment  | 

1 Answer 1

Reset to default 14

React reuses the synthetic event object so you can't use it in an async context as it is.

From the 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.

You either need to extract the information synchronously or call event.persist() to persist the object before using it in an async context.

Extracting the value synchronously:

onInputChanged = event => {
   const value = event.target.value;
   (async () => {
       await this.setState({ currentValue: value });
       this.props.onInputChange(e);
   })();           
}

Persisting the event before using it in an async context:

onInputChanged = event => {
   event.persist();
   (async () => {
       await this.setState({ currentValue: e.target.value });
       console.log('event', e.target);
       this.props.onInputChange(e);
   })();           
}
发布评论

评论列表(0)

  1. 暂无评论