Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

javascript - Accessing event.target inside callback in react

I have the following class snippet:

constructor(props) {
    super(props);

    this.timeout = null;
}

search = (e) => {
    clearTimeout(this.timeout);
    this.timeout = setTimeout(
        function(){ console.log(e.target); },
        500
    );
}

<input 
    type="text" 
    placeholder="Search by title or author" 
    onKeyPress={this.search} />

I can't get the set timeout to print the value from the event, is there something that i should be doing but i'm not?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

SyntheticEvent.

As per DOC:

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.

Example:

function onClick(event) {
   console.log(event.type); // => "click"
   const eventType = event.type; // => "click"

   setTimeout(function() {
      console.log(event.type); // => null
      console.log(eventType); // => "click"
   }, 0);    
}

How to access the values inside callback?

Storing value in a variable:

If you want to access the value in timeout callback function then store the value in a variable and use that variable instead of directly using the event object.

function onClick(event) {

   console.log(event.type); // => "click"

   const { type } = event;

   setTimeout(function() {
      console.log(type);   // => click
   }, 0);    
}

Using event.persist():

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.

function onClick(event) {

   event.persist();

   console.log(event.type); // => "click"

   setTimeout(function() {
      console.log(event.type); // => click
   }, 0);    
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...