我才刚刚开始在原生的React中掌握道具,所以我希望这是一个简单的解决方案。
我希望更新表单的状态以将用户带到表单的下一页,并且我也希望响应的状态也更新-两者都在用户按下按钮组件(onPress)时进行。
但是,我在console.log上看到的是更新状态功能立即运行,而不是在按下按钮时运行-因此它直接进入表单的第二个“页面”。
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) = ""
答案 0 :(得分:2)
您正在立即调用该函数,将其切换为:
<TouchableOpacity onPress={() => props.passHappiness('Excellent')}>
现在,您已经创建了一个匿名函数,该函数使用如下所示的参数“ Excellent”调用passHappiness
:
() => props.passHappiness('Excellent')
您还可以使用bind方法将参数“ excellent”“绑定”到函数
<TouchableOpacity onPress={props.passHappiness.bind(this,'Excellent')}>
有关绑定方法here的更多信息。