【问题标题】:How to relate each radio button to an object when mapping them映射时如何将每个单选按钮与对象相关联
【发布时间】:2020-06-30 17:33:17
【问题描述】:

我正在尝试制作一个对随机事物有疑问的应用,每个事物都有不同的类别。用户只需选择“是”或“否”,非常简单。

我有一个对象数组,每个对象都有类别和问题,

const questionsArray = [
    {
        category: 'sports',
        question: 'Do you practice soccer?'
    },
    {
        category: 'sports',
        question: 'Do you practice baseball?'
    },
    {
        category: 'routine',
        question: 'Do you like to watch movies?'
    },
    {
        category: 'routine',
        question: 'Do you like to play video games?'
    },
    {
        category: 'food',
        question: 'Do you like pasta?'
    },
    {
        category: 'food',
        question: 'Do you like cake?'
    },
]

在这里我循环遍历这个数组并向用户展示问题,

{questionsArray.map((data, i) => (
    <>
        <Text style={styles.text}>
            {i + 1} - {data.question}
        </Text>
        <Text style={{ color: "#fff", fontSize: 18, marginLeft: 10 }}>
            {data.atividades}
        </Text>
        <View style={styles.radioButtonContainer}>
            <RadioButton
                value="yes"
                color="#fff"
                uncheckedColor="#fff"
                status={checked === "yes" ? "checked" : "unchecked"}
                onPress={e => setChecked("yes")}
            />
            <Text style={styles.radioText}>Yes </Text>
        </View>
        <View style={styles.radioButtonContainer}>
            <RadioButton
                value="no"
                color="#fff"
                uncheckedColor="#fff"
                status={checked === "no" ? "checked" : "unchecked"}
                onPress={() => setChecked("no")}
            />
            <Text style={styles.radioText}>No </Text>
        </View>
    </>
))}

问题是我不知道如何将每个单选按钮与问题联系起来。我将这个库用于单选按钮https://callstack.github.io/react-native-paper/radio-button.html

当前的行为是当我更改一个单选按钮时,它们都会发生变化,这是有道理的,因为它们使用的是相同的状态。

最后,当用户按下提交答案按钮时,我想要一个像这样的 JSON 作为输出,它显示每个类别有多少“是”答案:

{
 "result": {
    "sports": 1,
    "routine": 1,
    "food": 2
   } 
}

这里是完整代码:https://snack.expo.io/UhoiXh4ri

【问题讨论】:

  • 使用嵌套数组不是更好吗?就像,你有一个类别,然后在它下面 - 你有一系列与类别相关的问题。重复模式。

标签: reactjs react-native


【解决方案1】:

我认为,如果您根据它们的 name 属性对单选按钮进行分组,它应该可以工作。

name={data.category} 添加到两个单选按钮

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-27
    • 2016-03-07
    • 2016-10-26
    • 2016-05-23
    • 2019-10-24
    • 1970-01-01
    • 2011-06-09
    相关资源
    最近更新 更多