1

我编写了这段代码(在 Expo.io 中)将 JSON 数据类别显示为标题,将 subs 显示为列表,它使用 .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,
},
});

它工作正常,但它显示了主要类别旁边的 subs,我希望它显示如下:

Burger 
   Vegi  
   Turkey 
Egg 
   Omelete  
   Scrambled 
4

2 回答 2

0

您应该像这样将每个<Text/>内部分开<View/>

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

您可以在样式中为 subItem 添加边距:

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    width: '100%',
    borderWidth: 1,
  },
  subItem: {
    marginLeft: 5,
  },
});
于 2021-02-24T07:45:34.693 回答
0

试试这个方法

<View>
        {this.state.category.map((item) => (
          <Text>
            {item.name}
          </Text>
            {item.items.map((sub) => (
              <Text style={{marginLeft:30}}>{sub.name}</Text>
            ))}
        ))}
</View>
于 2021-02-24T07:46:18.313 回答