反应本机 |为什么我的函数 运行 立即执行,而不仅仅是 onPress?

React Native | Why is my function running immediately, rather than just onPress?

我刚刚开始掌握 React Native 中的道具,所以我希望这是一个简单的解决方案。

我希望更新表单的状态以将用户带到表单中的下一页,并且我希望响应的状态也更新 - 当用户按下按钮组件 (onPress) 时。

但是,我在 console.log 时看到的是更新状态函数立即 运行,而不是在按下按钮时 - 所以它直接进入第二个 "page" 的形式。

表单组件

import React, {useState} from 'react';
import { View, Text} from 'react-native';
import Happiness from './Happiness';

const StarterForm = () => {
    const [formStage, setFormStage] = useState(1)
    const [happinessLevel, setHappinessLevel] = useState('')

  console.log(formStage)
  console.log(happinessLevel)

  const increaseTheStage = (happiness) => {
      setHappinessLevel(happiness)
      setFormStage(formStage +1)
  }

  switch (formStage) {
    case 1:
      return (
        <Happiness 
        passHappiness={increaseTheStage}
        />
      )
    case 2: 
        return (
          <Text>This is the case of two</Text>
        )
  }
}

export default StarterForm;

幸福成分

import React from 'react';
import { View, Text, TouchableOpacity } from 'react-native';

const Happiness = (props) => {
  return (
    <View>
            <Text>Which of the following best classifies your happiness?</Text>
            <TouchableOpacity onPress={props.passHappiness('Excellent')}>
              <Text>Excellent</Text>
            </TouchableOpacity>
        </View>
  )
}


export default Happiness;

预期结果

我希望第一个屏幕打开时出现以下情况:

console.log(formStage) = "1" 
console.log(happinessLevel) = "" 

使用匿名函数

您正在调用该函数,将其切换为:

<TouchableOpacity onPress={() => props.passHappiness('Excellent')}>

现在您已经创建了一个匿名函数,该函数使用参数 'Excellent' 调用 passHappiness,如下所示:

() => props.passHappiness('Excellent')

使用绑定

也可以使用bind方法"bind"参数"excellent"到函数

<TouchableOpacity onPress={props.passHappiness.bind(this,'Excellent')}>

关于绑定方法的更多信息here