Accessing event.target inside callback in react

前端 未结 4 1541
借酒劲吻你
借酒劲吻你 2020-11-28 14:00

I have the following class snippet:

constructor(props) {
    super(props);

    this.timeout = null;
}

search = (e) => {
    clearTimeout(this.timeout);
         


        
4条回答
  •  青春惊慌失措
    2020-11-28 14:49

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

提交回复
热议问题