简体   繁体   English

我不明白我的 onPress 的反应

[英]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.当我同时学习 Javascript 时,我想我应该在我的函数后面加上括号。 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.现在有了这个改变,如果我修改 TextInput 中的文本,我的“myFunction”就会被系统地调用。

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.我们都喜欢它们,但在 React 中使用它们时应该谨慎。 Arrow functions are great, they let us quickly create new javascript function short hand.箭头函数很棒,它们让我们可以快速创建新的 javascript 函数简写。 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.在 Javascript 中的大多数情况下,这不是一个真正的问题。 When it comes to the React render method this can quickly become an issue.当涉及到 React 渲染方法时,这很快就会成为一个问题。

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.但实际上,React 在执行这个 render 方法的时候,总会看到一个新的函数。 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.这导致 React 认为我们的观点发生了一些变化,而实际上什么都没有。

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.每次更改文本时,组件的状态也会更改,因为您使用了onChangeText={(text) => setText(text)} ,这会导致您的组件重新渲染。

During re-render, the following line is also executed.在重新渲染期间,还会执行以下行。 In this line you are calling myFunction.在这一行中,您正在调用 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.简而言之,更改文本会导致状态更新,进而导致重新渲染,并在重新渲染期间调用 myFunction。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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