将 React Native 状态设置为 Button 标题道具
set React Native state to the Button title prop
我不知道如何更新我的基本 React Native 应用程序中的状态,使其等于 Button 的 title 道具中的任何内容。
我试过将状态设置为{title},但没有成功。我正在使用 useState 挂钩,所以我认为我不需要使用 "this."。
import React, {useState} from 'react';
import { View, Text, Button } from 'react-native';
const StarterForm = () => {
const [formStage, setFormStage] = useState(1)
const [feelings, setFeelings] = useState('')
console.log(feelings)
const updateFormStage = () => {
setFormStage(formStage + 1)
setFeelings({title})
}
switch (formStage) {
case 1:
return (
<View>
<Text>How are you?</Text>
<Button title="Excellent" onPress={updateFormStage}/>
</View>
)
case 2:
return (
<Text>This is the case of two</Text>
)
}
};
在示例中,我希望 console.log(感觉)在按下按钮后等于 "Excellent"。
您可以为此使用 ref
,但我认为解决问题的最佳方法是将 "Excellent"
存储在变量中,然后使用 onPress={() => updateFormStage(mVariable)}
一种方法是为您定义的按钮设置引用,点击它后,从引用中检索数据,如下所示:
<Button ref={ref => { this.button = ref; }}
title="Excellent"
onPress={this.updateFormStage} />
您可以使用 this.button.title
:
通过按钮引用访问您的标题
updateFormStage = () => {
console.log(this.button.title);
}
我不知道如何更新我的基本 React Native 应用程序中的状态,使其等于 Button 的 title 道具中的任何内容。
我试过将状态设置为{title},但没有成功。我正在使用 useState 挂钩,所以我认为我不需要使用 "this."。
import React, {useState} from 'react';
import { View, Text, Button } from 'react-native';
const StarterForm = () => {
const [formStage, setFormStage] = useState(1)
const [feelings, setFeelings] = useState('')
console.log(feelings)
const updateFormStage = () => {
setFormStage(formStage + 1)
setFeelings({title})
}
switch (formStage) {
case 1:
return (
<View>
<Text>How are you?</Text>
<Button title="Excellent" onPress={updateFormStage}/>
</View>
)
case 2:
return (
<Text>This is the case of two</Text>
)
}
};
在示例中,我希望 console.log(感觉)在按下按钮后等于 "Excellent"。
您可以为此使用 ref
,但我认为解决问题的最佳方法是将 "Excellent"
存储在变量中,然后使用 onPress={() => updateFormStage(mVariable)}
一种方法是为您定义的按钮设置引用,点击它后,从引用中检索数据,如下所示:
<Button ref={ref => { this.button = ref; }}
title="Excellent"
onPress={this.updateFormStage} />
您可以使用 this.button.title
:
updateFormStage = () => {
console.log(this.button.title);
}