Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

123
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda