Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

150
Visualizações
Why is the this keyword inside clickHandler undefined?

I was following a YouTube tutorial on eventHandling when I got confused with the implementation of this keyword.

In the code below, the this keyword inside of clickHandler function gives the value of undefined. The instructor said that it is because that's how JavaScript works. But when I searched online I found out that this keyword when used inside a function of a class, points to the object itself.

This might be a stupid question to ask but since I am new to JavaScript any help will be appreciated

class EventBind extends Component {
  constructor(props) {
    super(props);

    this.state = {
      message: "Hello",
    };
  }

  clickHandler() {
    // this.setState({
    //   message : 'Goodbye'
    // })
    console.log(this);
  }

  render() {
    return (
      <div>
        <div>{this.state.message}</div>
        <button onClick = {this.clickHandler}>Click</button>
      </div>
    );
  }
}

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This is cause you have not bound the clickHandler to this. Try below code

class EventBind extends Component {
  constructor(props) {
    super(props);
    this.clickHandler = this.clickHandler.bind(this);
    ...

  }
  clickHandler() {
    ...
  }
  ...
  
}

See here for more info: https://reactjs.org/docs/faq-functions.html

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda