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

216
Vistas
What are the aspects of JS binding?

Have the following simpliest component.

class App extends Component {
  constructor(props) {
    super(props);
    console.log(this);
    this.state = {
      name: "John"
    }
  }

  clickHandler() {
    this.setState({
      name: "Mark"
    })
  };

  render() {
    return (
      <div className="App">
        {this.state.name}
        <button onClick={this.clickHandler.bind(this)}></button>
      </div>
    )
  };
}

export default App;

If I write that

<button onClick={this.clickHandler}></button>

it says that this in

this.setState({
      name: "Mark"
    })

is undefined. That row

<button onClick={console.log(this)}></button>

shows that this is App. So if this is App why clickHandler does not bind automatically to that object before the dot?

<button onClick={this.clickHandler}></button>

As far as I understand in "context.function" the context should be bound to the function. Or it only works for "context.function()"?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Or it only works for "context.function()"?

That's exactly right. It depends on where the function is invoked.

Doing

<button onClick={this.clickHandler}></button>

passes the clickHandler as a parameter. React's internals see something not completely dissimilar to:

function button({ onClick }) {
  // ...
  theActualDOMButtonElement.addEventListener('click', onClick);
}

or

function button({ onClick }) {
  // ...
  theActualDOMButtonElement.addEventListener('click', (e) => {
    const reactCreatedSyntheticEvent = retrieveSyntheticEvent(e);
    onClick(reactCreatedSyntheticEvent);
  });
}

You're passing the this.clickHandler as a parameter, not invoking it immediately - since it gets invoked later, and how it's invoked later determines the this, you can't just do onClick={this.clickHandler} without making sure the this is correct, such as invoking the function inline, or by using a class field, or by using a functional component.

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