How to get child of json in react native

时间:2019-01-07 13:39:31

标签: react-native fetch

I need to get src from json file.

JSON:

[
  {
    "id": 38,
    "name": "Product",
    "images": [
        {
            "id": 26,
            "src": "https://example.com/image.png",
            "name": "pants",
            "alt": ""
        }
    ],
    ...

Codes:

<ListView
        dataSource={this.state.dataSource}
        renderRow={(rowData)=>
          <View style={{height:40}}>
            <Text>{rowData.images}</Text>
          </View>
        }
        />

I can show id or name by rowData.name, but images src not working.

2 个答案:

答案 0 :(得分:1)

You need to loop through the array of images to access the src property.

You can achieve that like this (untested):

<ListView
        dataSource={this.state.dataSource}
        renderRow={ (rowData)=> {
         return rowData.images.map( (image, index) => {
            return (<View key={index}><Text> { image.src } </Text></View>)
          })
        }}
/>

答案 1 :(得分:0)

由于驻留在images键中的datatype是一个数组,我认为从数组中获取索引将有助于您完成所需的工作。

您可以尝试rowData.images[0]吗?我要添加的后续代码取决于您是否希望有多个图像,以及要对这些图像执行什么操作。

如果要显示图像,则需要使用React Native Image组件。

<View style={{height:40}}>
  <Image
    style={{ width: 50, height: 50 }}
    source={{ uri: dataRow.images[0].src }}
  />
</View>