Access event.target inside callback in reaction

I have the following class fragment:

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 given timeout for printing the value from the event, is there something I should do, but I don’t?

+4
source share
4 answers

SyntheticEvent .

By DOC :

SyntheticEvent integrates. This means that the SyntheticEvent object will be reused and all properties will be invalidated after the event callback is called. 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 values ​​inside a callback?

Storing a value in a variable:

timeout, .

event.persist():

, event.persist() , .

+6

:

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

}

, , babel-plugin-transform-class-properties. .

+3

It's hard to say without seeing your onKeypress method, but this can be a problem. Try linking your search to the constructor.

constructor (props) {
    super(props);

    this.timeout = null;
    this.search = this.search.bind(this);
}
0
source

Are you going to make timeouta fortune?

My suggestion would be this:

constructor(props) {
    super(props);
    this.state = {
       timeout: null
    }
}

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

}
0
source

Source: https://habr.com/ru/post/1682936/


All Articles