问题描述
<RadioButtonRN
BoxStyle={{
height: hp("6%"),width: wp("80%"),}}
activeColor="white"
BoxActiveBgColor="red"
textColor="black"
textStyle={{ fontWeight: "bold" }}
data={goal}
selectedBtn={(e) => console.log(e)}
/>
<View style={{ alignItems: "center" }}>
<Text style={{ color: "red",fontSize: 15,top: hp("5%") }}>
How much would you like to gain per week?
</Text>
<RadioButtonRN
style={{ top: hp("10%") }}
BoxStyle={{
height: hp("6%"),}}
activeColor="white"
BoxActiveBgColor="red"
textColor="black"
textStyle={{ fontWeight: "bold" }}
data={details}
selectedBtn={(e) => console.log(e)}
/>
</View>
const goal = [
{
label: "Muscle Gain",},{
label: "Fat Loss",{
label: "Maintaining",];
const details = [
{
label: "1 pound per week",{
label: "0.5 pounds per week",{
label: "0.25 pounds per week",];
嗨,我是编程新手,我想知道如何根据单选按钮的选择更改视图组件。例如,如果用户选择 Muscle Gain,它会显示 View 组件说“您希望每周获得多少?”如果用户选择 Fat Loss,它会显示一个 View 组件,上面写着“你想减多少?”
解决方法
你可以用这样的状态来管理功能组件
const [selectedGoal,setSelctedGoal] = React.useState(1)
return (
<View style={styles.container}>
<RadioButtonRN
boxStyle={{
height: "6%",width: "80%",}}
activeColor="white"
boxActiveBgColor="red"
textColor="black"
textStyle={{ fontWeight: "bold" }}
data={goal}
initial={selectedGoal}
selectedBtn={(e) => setSelctedGoal(e.id)} //set Selected id
/>
<Text style={{ color: "red",fontSize: 15,top: "5%" }}>
How much would you like to {selectedGoal == 1 ? 'Gain' : selectedGoal== 2 ? 'Lose':'Maintain'} per week?
</Text>
</View>
);
对于类组件
constructor(props) {
super(props);
this.state = { selectedGoal: 1 };
}
render(){
const {selectedGoal} = this.state
return (
<View style={styles.container}>
<RadioButtonRN
boxStyle={{
height: "6%",}}
activeColor="white"
boxActiveBgColor="red"
textColor="black"
textStyle={{ fontWeight: "bold" }}
data={goal}
initial={selectedGoal}
selectedBtn={(e) => {this.setState({selectedGoal:e.id})}} //set Selected id
/>
<Text style={{ color: "red",top: "5%" }}>
How much would you like to {selectedGoal == 1 ? 'Gain' : selectedGoal== 2 ? 'Lose':'Maintain'} per week?
</Text>
</View>
);
}
您可以为选定的目标使用 id
const goal = [
{
label: "Muscle Gain",id:1
},{
label: "Fat Loss",id:2
},{
label: "Maintaining",id:3
},];