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

101
Visualizações
I don't understand the reaction of my onPress

I created a short test to get an explanation of how my code reacts.

Basically I want to call a function only when I press my button. No problem, the code below works.

// Components/Test.js
import React, { useState } from "react";
import { View, StyleSheet, TextInput, Button } from "react-native";

function Test(props) {
  const [text, setText] = useState("");

  const myFunction = () => {
    console.log("test");
  };

  return (
    <View style={styles.container}>
      <TextInput
        style={{ borderWidth: 1, width: "70%" }}
        onChangeText={(text) => setText(text)}
      />
      <Button title="Button" onPress={myFunction} />
    </View>
  );
}

// Styles
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
  },
});

export default Test;

As I'm learning Javascript at the same time, I thought I'd put parentheses after my function. Technically, if I want to pass parameters to my function, I thought I should do it like this. <Button title="Button" onPress={myFunction()} />

And now with this change, my "myFunction" is called systematically if I modify the text in TextInput.

Can someone explain what is going on? Thank you !

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

0

You should use arrow function

<Button title="Button" onPress={() => myFunction('parameter')} />

if you just call like

<Button title="Button" onPress={myFunction()} /> // its calling function directly

Its call the function directly

about 4 years ago · Juan Pablo Isaza Relatório

0

Arrow Functions:

We all love them, but should be cautious when using them with React. Arrow functions are great, they let us quickly create new javascript function short hand. The consequence of this is exactly that, it creates a new function every time it is executed. For the most part in Javascript this isn’t a real issue. When it comes to the React render method this can quickly become an issue.

render(){
 return (
  <View>
   <TouchableOpacity onPress={() => console.log('Hello!')}>
     Click Me
   </TouchableOpacity>
  </View>
 )
}

So what could be the harm here, the button is simply just logging out a string on press. But in fact, when React executes this render method it will always see a new function. The arrow function returns a new function every time. This causes React to think something has changed in our view, when in fact nothing has.

logHello(){
 console.log('Hello!');
}
render(){
 return (
  <View>
   <TouchableOpacity onPress={this.logHello}>
     Click Me
   </TouchableOpacity>
  </View>
 )
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Everytime you change the text, the state of the component also changes becuase, you've used onChangeText={(text) => setText(text)}, this causes your component to re-render.

During re-render, the following line is also executed. In this line you are calling myFunction. <Button title="Button" onPress={myFunction()} />

In short, changing the text causes state update, which in turn causes a re-render, and during that re-render myFunction is called.

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