Pass THIS into the [duplicate] function

0

Hi, I have a function in React and I would like to move this inside of it to be able to use the states, someone knows how? Thank you very much for your help

  constructor(props) {
    super(props);
    this.state = {
      message: 'Login'
    }
  }

  componentDidMount(){
  var working = false;
  var y = document.getElementsByClassName('login');
  var login = y[0];

  login.addEventListener('submit', function(e) {
    e.preventDefault();
    if (working) return;
    working = true;
    var state = {};
    state = login.querySelectorAll('button > .state');
    login.classList.add('loading');
    this.setState({message: 'Authenticating'});
    setTimeout(function() {
      login.classList.add('ok');
      this.setState({message: 'Welcome Back!'});
      setTimeout(function() {
        this.setState({message: 'Log In'});
        login.classList.remove('ok loading');
        working = false;
      }, 4000);
    }, 3000);
  });
  }
    
asked by Santiago D'Antuoni 10.01.2018 в 16:09
source

1 answer

1

Options:

In the method componentDidMount define a variable let _this=this; and use it in the rest of the functions declared inside (those of the setTimeout and that of the event listener). You will be creating a "closure" (closure, in English) that will solve the problem.

Another solution is to declare the functions with an arrow:

 login.addEventListener('submit', (e) => {
    e.preventDefault();
    if (working) return;
    working = true;
    var state = {};
    state = login.querySelectorAll('button > .state');
    login.classList.add('loading');
    this.setState({message: 'Authenticating'});
    setTimeout(() => {
      login.classList.add('ok');
      this.setState({message: 'Welcome Back!'});
      setTimeout(() => {
        this.setState({message: 'Log In'});
        login.classList.remove('ok loading');
        working = false;
      }, 4000);
    }, 3000);
  });

A small example with arrow functions and without them, and a third example of a closure:

class Test {

  constructor() {
    this.texto="hola";
  }

  metodo() {
   setTimeout(()=>{
    console.log(this.texto);
   });
  }
}

let test=new Test();
test.metodo();

class Test2 {

  constructor() {
    this.texto="no se escribirá nada";
  }

  metodo() {
   setTimeout(function() {
    console.log(this.texto);
   });
  }
}

let test2= new Test2();
test2.metodo();

class Test3 {

  constructor() {
    this.texto="clausura";
  }

  metodo() {
  let _this=this;
   setTimeout(function() {
    console.log(_this.texto);
   });
  }
}

let test3= new Test3();
test3.metodo();
    
answered by 10.01.2018 / 16:36
source