【问题标题】:Dynamically creating elements based on json in REACT NATIVE在 REACT NATIVE 中基于 json 动态创建元素
【发布时间】:2017-12-14 04:27:20
【问题描述】:

我是这个论坛的新手,也是 React Native 的新手。谁能给我写一段代码来创建基于 json 的表单元素(图像、拨动开关)。

我的 JSON 看起来像

[{“消费者”:“S1”,“状态”:“假”},{“消费者”:“S2”,“状态”: “假”},{“消费者”:“S3”,“状态”:“真”},{“消费者”:“S4”, “状态”:“假”},{“消费者”:“S7”,“状态”:“假”}]

我想为每种模式获取 i,例如:

<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>

【问题讨论】:

    标签: javascript json reactjs react-native


    【解决方案1】:

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

    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>
          ]
        })}
      );
    }
    

    【讨论】:

    • 谢谢布赖恩,但是将这个 JSON 读取给消费者变量的最简单方法是什么以及在什么位置,我的 JSON 实际上是在 link
    • 您想从 API 调用中读取 JSON 吗?如果您从其他地方获取它,我建议您在 componentDidMount() 中获取 JSON 并使用 setState 将其存储在您的组件状态中,然后映射它而不是渲染函数中的变量。
    • 或者将 JSON 作为 prop 从父组件向下传递。
    • 哇,布莱恩,你真快!你能把一大块代码传给我吗,因为我仍然在这片水域中不安全地漂浮:D
    • 谢谢,恩迪。我可以,但我仍然不确定你是如何获得 JSON 的。它是硬编码的,是从外部来源获取的,是从父母那里传下来的吗?
    猜你喜欢
    • 1970-01-01
    • 2021-12-06
    • 1970-01-01
    • 1970-01-01
    • 2022-12-22
    • 1970-01-01
    • 2018-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多