简体   繁体   中英

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 !

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM