Home > Software design >  I don't understand the reaction of my onPress
I don't understand the reaction of my onPress

Time:10-21

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 !

CodePudding user response:

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

CodePudding user response:

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>
 )
}
  • Related