在REACT NATIVE中基于json动态创建元素

时间:2017-12-14 04:27:20

标签: javascript json reactjs react-native

我是这个论坛的新手,也是React Native的新手。有人可以给我写一段代码来创建基于json的表单元素(图像,切换开关)。

我的JSON看起来像

  

[{"消费者":" S1","状态":"错误"},{"消费者和#34 ;:" S2","状态":   "错误"},{"消费者":" S3","状态":" True"},{& #34;消费者":" S4",   "状态":"错误"},{"消费者":" S7","状态":&#34 ;假"}]

我想为每个模式得到一个像:

<View style={{width: '30%', height: 200}}>
          <Image
            source={
              require('../assets/images/s1.png') //sx
            }
            style={styles.welcomeImage}
          />

        </View>
        <View style={{width: '30%', height: 200}}>
          <Switch
            //here get status of s1..s8
        </View>

1 个答案:

答案 0 :(得分:2)

您应该通过数组进行映射。像这样:

render() {
  var consumers = [{ "consumer": "S1", "status": "False"},{ "consumer": "S2", "status": "False"},{"consumer": "S3", "status": "True"},{ "consumer": "S4", "status": "False"},{ "consumer": "S7", "status": "False"}];
  return (
    {consumers.map((c, i) => {
      return [
        <View style={{width: '30%', height: 200}}>
          <Image
            source={require('../assets/images/' + c.consumer + '.png')}
            style={styles.welcomeImage}
          />
        </View>
        <View style={{width: '30%', height: 200}}>
          <Switch value={c.status} />
        </View>
      ]
    })}
  );
}