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

99
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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