【问题标题】:React Native, Display JSON data as a titles and lists (Categories and subcategoriesReact Native,将 JSON 数据显示为标题和列表(类别和子类别
【发布时间】:2021-02-24 07:25:20
【问题描述】:

我制作了这个code(住在 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,
},
});

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

Burger 
   Vegi  
   Turkey 
Egg 
   Omelete  
   Scrambled 

【问题讨论】:

    标签: javascript html json react-native


    【解决方案1】:

    您应该像这样在&lt;View/&gt; 中分隔每个&lt;Text/&gt;

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

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

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

    【讨论】:

      【解决方案2】:

      试试这个方法

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

      【讨论】:

        猜你喜欢
        • 2021-06-18
        • 2012-10-14
        • 1970-01-01
        • 2011-07-14
        • 2018-11-13
        • 1970-01-01
        • 2013-05-14
        • 2016-08-13
        • 2018-12-20
        相关资源
        最近更新 更多