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

122
Visualizações
ReactJS onClick event cant call its function

I have problem here with this.greet() is undefined i have to bind onlick event dirrently to work, any ideas how to fix it ?

import React from 'react';

export default class Example1 extends React.Component {
    constructor() {
        super();
        this.message = {
            greeting: 'Hello',
            name: 'World',
        };
    }

    greet() {
        const { greeting, name } = this.message;
        console.log(`${greeting} ${name}!`);
    }

    onClick() {
        try {
            this.greet();
        } catch (e) {
            console.error('Why have I failed? Can you fix me?');
        }
    }
    
    render() {
        return (
            <div>
                <button onClick={this.onClick}>Greet the world</button>
            </div>
        );
    }
}

i have tried many other ways but it didnt work out anyway.

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

0

if you want have "this" in your class component you should add props inside constructor invocation and also into the super

constructor(props) {
    super(props);
    this.greet = this.greet.bind(this) // need's to be bounded
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Problem is this keyword. This is because of the way this works in javascript.

this loses it's context when it gets used in callbacks.

There are two solutions for this problem. But I would recommend the arrow function solution the most.

  1. Bind this in the onClick callback.

     onClick() {
         try {
             this.greet();
         } catch (e) {
             console.error('Why have I failed? Can you fix me?');
         }
     }
    
     render() {
         return (
             <div>
                 <button onClick={this.onClick.bind(this)}>Greet the world</button>
             </div>
         );
     }
    
  2. Use arrow functions for defining callbacks, ( personally recommended )

     onClick = () => {
         try {
             this.greet();
         } catch (e) {
             console.error('Why have I failed? Can you fix me?');
         }
     }
    
     render() {
         return (
             <div>
                 <button onClick={this.onClick}>Greet the world</button>
             </div>
         );
     }
    
about 4 years ago · Juan Pablo Isaza Relatório

0

You lost this reference, you have to bind your functions:

<button onClick={this.onClick.bind(this)}>Greet the world</button>

or pass an arrow function

<button onClick={() => this.onClick()}>Greet the world</button>
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