如何在React Native中为单选按钮提供获取api?

时间:2018-12-19 10:45:17

标签: javascript reactjs react-native radio-button jsx

我正在使用 this package for radio button。我正在尝试在单选按钮中显示api的结果.api响应包含4个选项。所以我想用4个单选按钮渲染文本,但是现在我只得到一个带有文本的单选按钮。这就是

enter image description here

这是代码

{
  this.state.data.map(a => (
    <Card>
      <CardItem>
        <Text style={styl.textStyle}>
          {(a.content = a.content.replace(/(<([^>]+)>)/gi, ""))}
        </Text>
      </CardItem>
      <CardItem>
        <RadioGroup
          size={24}
          thickness={2}
          color="#9575b2"
          highlightColor="#ccc8b9"
          selectedIndex={1}
          onSelect={item => this._onSelect(item, i++)}
        >
          <RadioButton value={a.options}>
            <Text>{a.options}</Text>
          </RadioButton>
        </RadioGroup>
      </CardItem>
    </Card>
  ));
}

json响应

{
                "type": "single",
                "hint": "",
                "explanation": ".",
                "content": "<p>3. The World Banks’ Doing Business Report 2018 was the fifteenth edition since its inception in 2003. Examine the following statements about the Report and select the correct answer using the codes given below.</p>\n<p>I. Doing Business uses 11 indicator sets to measure aspects of business regulation that matter for entrepreneurship.</p>\n<p>II. India is one of the 10 economies that improved the most in the areas measured by Doing Business as per the 2018 Report.</p>\n<p>III. South Asia is the only region not represented in the top 50 ranking for ease of doing business.</p>\n",
                "options": [
                    "(a) I, II and III are correct ",
                    "(b) Only I is correct ",
                    "(c) Only I and II are correct ",
                    "(d) Only III is correct "
                ],
                "correct": "1",
                "marks": 4,
                "user_marks": 0,
                "status": 0,
                "marked": null,
                "auto": 1
            },

请帮助。非常感谢您。

2 个答案:

答案 0 :(得分:1)

When you get the response extract the option values from in state variable and then use that state variable where ever you want

.then((response) => response.json())
        .then((responseJson) => {
          this.setState({
            option_1_value:responseJson.options[0],
            option_2_value:responseJson.options[1],
        option_3_value:responseJson.options[2],
        option_4_value:responseJson.options[3],
          })
 })
 .catch((error) => {
          console.error(error);
 });

答案 1 :(得分:1)

You can do something like this to make loop inside radiogroup to render your radio buttons according to json response.

<RadioGroup
  size={24}
  thickness={2}
  color="#9575b2"
  highlightColor="#ccc8b9"
  selectedIndex={1}
  onSelect={item => this._onSelect(item, i++)}
  >
  {
    a.options.map((item, key) =>
    (
      <RadioButton value={item}>
        <Text>{item}</Text>
      </RadioButton>
    ))
  }
</RadioGroup>