React Native,显示JSON数据作为标题和列表(类别和子类别)



我做了这个代码(在Expo.io中)来显示JSON数据类别作为标题和子列表,它使用.map()从数组中检索数据。

import React, { useState } from 'react';
import { Text, View, StyleSheet, Button, FlatList } from 'react-native';
export default class J extends React.Component {
constructor() {
super();
this.state = {
id: '1',
name: 'Breakfast',
category: [
{
id: '1',
name: 'Burger',
items: [
{ id: '1', name: 'Vegi' },
{ id: '2', name: 'Turkey' },
],
},
{
id: '1',
name: 'Egg',
items: [
{ id: '1', name: 'Omelete' },
{ id: '2', name: 'Scrambled' },
],
},
],
};
}
render() {
return (
<View>
{this.state.category.map((item) => (
<Text>
{item.name}
{item.items.map((sub) => (
<Text> {sub.name} </Text>
))}
</Text>
))}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
width: '100%',
borderWidth: 1,
},
});

它工作得很好,但是它显示了主类别旁边的子类别,我希望它像这样显示:

Burger 
Vegi  
Turkey 
Egg 
Omelete  
Scrambled 

您应该像这样在<View/>中分隔每个<Text/>:

render() {
return (
<View style={styles.container}>
{this.state.category.map((item) => (
<View>
<Text>{item.name}</Text>
{item.items.map((sub) => (
<Text style={styles.subItem}>{sub.name}</Text>
))}
</View>
))}
</View>
);
}

你可以在styles:

中为subItem添加边距
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
width: '100%',
borderWidth: 1,
},
subItem: {
marginLeft: 5,
},
});

试试这个

<View>
{this.state.category.map((item) => (
<Text>
{item.name}
</Text>
{item.items.map((sub) => (
<Text style={{marginLeft:30}}>{sub.name}</Text>
))}
))}
</View>

最新更新