【问题标题】:How to add radio button in react native?如何在本机反应中添加单选按钮?
【发布时间】:2018-08-17 14:36:43
【问题描述】:

我想在 react native 中添加单选按钮,这很简单,我已经做到了。但问题是我想在从服务器获取内容时循环通过单选按钮。所以列表取决于正在更改的获取项目的数量。我获取的数据如下

json 数据

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

好吧,我在CardSection 组件内显示content。我想用相应的单选按钮循环selection 数组。我正在使用映射方法来呈现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数组中的第一个值。但是如何使用数组中每个项目的单选按钮循环遍历呢?

【问题讨论】:

标签: javascript for-loop react-native radio-button jsx


【解决方案1】:

您可以通过以下方式循环

我假设你使用的是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>
  )
}

【讨论】:

  • 实际上我正在使用基于类的组件,因为我正在从服务器获取数据。那么我可以使用单独的render 方法吗?
  • 不,你不能,只在类中使用_setActive和render
  • 您可能需要格式化selection 数组以根据您的需要在formatArray 函数中设置label
  • 好的,我在哪里获取渲染中的selection 数组?我的意思是在CardSection 里面?我已经根据你的回答更新了我的问题,请帮忙。
  • 我需要像这样给arr.map((item,index) =&gt; newArr.push({'label': index, value: a.selection}))
猜你喜欢
  • 2019-06-21
  • 2022-08-16
  • 1970-01-01
  • 1970-01-01
  • 2019-05-19
  • 1970-01-01
  • 1970-01-01
  • 2018-08-17
  • 2021-09-23
相关资源
最近更新 更多