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

114
Visualizações
Can't understand onPress behaviour TouchableOpacity by calling function in different ways

I have a react-native class component, in which I have a counter function:

counter() {
  console.log("hi")
  this.setState({count:this.state.count+1})
}

I have a state named count initialized to 0. I have a text which displays the count value as well.

In my render, in the return, im trying to call this counter function onPress of a TouchableOpacity. I tried 2 things in the onPress with 2 different outputs. Can someone explain why i got these outputs for each case? :

  1. onPress = {() => this.counter()}

here, state value was updating and displaying, and i got the console.log as well (desired output)

  1. onPress = {this.counter}

here, i got the console.log, but the state value wasn't updating. why isnt state updating here?

Thanks in advance

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

0

If you want to call counter function without arrow pattern in class component then you need to call bind in constructor block for counter function

constructor(props) {
    super(props);
    this.counter = this.counter.bind(this);
}

counter() {
    this.setState({ count: this.state.count + 1 });
}
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