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

222
Visualizações
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 Respostas
Responde à pergunta

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 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