Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

125
Views
El evento ReactJS onClick no puede llamar a su función

Tengo un problema aquí con this.greet() no está definido, tengo que vincular el evento onlick directamente para que funcione, ¿alguna idea de cómo solucionarlo?

 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> ); } }

He intentado muchas otras formas, pero no funcionó de todos modos.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

si desea tener "esto" en su componente de clase, debe agregar accesorios dentro de la invocación del constructor y también en el super

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

0

El problema es this palabra clave. Esto se debe a la forma en this funciona en javascript.

this pierde su contexto cuando se usa en devoluciones de llamada.

Hay dos soluciones para este problema. Pero recomendaría la solución de función de flecha más.

  1. Enlace esto en la devolución de llamada onClick .

     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 funciones de flecha para definir devoluciones de llamada (recomendado personalmente)

     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 Report

0

Perdiste this referencia, tienes que vincular tus funciones:

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

o pasar una función de flecha

 <button onClick={() => this.onClick()}>Greet the world</button>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!