繁体   English   中英

如何在React Native中添加单选按钮?

[英]How to add radio button in react native?

我想在react native中添加单选按钮,这非常简单并且已经完成了。 但是事情是我想在从服务器获取内容时通过单选按钮循环播放,因此列表取决于正在更改的获取项目的数量。我正在获取的数据如下

json资料

{
    "data": [{
        "content": "question",
        "selection": [
            "(a).option1",
            "(b).option2 ",
            "(c).option3 ",
            "(d).option4 "
        ],
        "correct": "4",
    }]
}

好吧,我正在CardSection组件内部显示content 。我想使用相应的单选按钮遍历selection数组。我正在使用map方法渲染data 所以对于selection我应该使用什么呢?for循环可以吗?但是我不知道该怎么做,请帮忙。

更新

    const formatArray = (arr) => {
  let newArr = []
  arr.map((item, index) => newArr.push({'label': index, value: item}))
  return newArr
}
class QASection extends Component{
render() {

    _setActive = (active) => this.setState({this.setState({selected:value})})

    return(
    {this.state.details.map(a =>
    <Card>
    <CardSection>
    <Text>{a.content}</Text>
    </CardSection>
    <CardSection>
        <RadioForm
          radio_props={radio_props}
          initial={0}
          itemShowKey="label"
          itemRealKey="value"
          dataSource={formatArray(data)}
          onPress={onPress}
        />
<CardSection data={data} key={index} onPress={this._setActive} />
    </Card>
    )}
    );
     } 
}

通过渲染selection[0] ,它将为我提供selection数组中的第一个值。 但是,如何使用单选按钮遍历数组中的每个项目呢?

您可以按以下方式循环

我假设您使用的是react-native-radio-form

const formatArray = (arr) => {
  let newArr = []
  arr.map((item, index) => newArr.push({'label': index, value: item}))
  return newArr
}

const YourCardComponent = ({data, onPress}) => {
  return (
    <Card>
      <CardSection>
        <Text>{data.content}</Text>
      </CardSection>
      <CardSection>
        <RadioForm
          radio_props={radio_props}
          itemShowKey="label"
          itemRealKey="value"
          dataSource={formatArray(data.selection)}
          onPress={onPress}
          // ... other props as required
        />
      </CardSection>
    </Card>
  )
}

    // Inside the class


_setActive = (active) => this.setState({selected:value})

render () {
  const {details} = this.state
  return (
    <View>
      {details.map((data, index) => (
        <YourCardComponent data={data} key={index} onPress={this._setActive} />
      ))}
    </View>
  )
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM