You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native多条件创建组件:账单数据结构化展示需求

嘿,我来帮你搞定这个React Native的账单展示组件!咱们先明确需求:把给定的账单数据按年份分组,每个年份下的账单再按月份从小到大排序,然后用Text组件规整地展示出来对吧?

第一步:数据预处理(用Lodash简化操作)

你已经引入了Lodash,正好可以用它的groupBy和sortBy方法快速处理数据:

  • 先用_.groupBy把账单按year字段分组
  • 再对每个年份下的账单列表,用_.sortBy按month字段升序排序
  • 最后把年份的键值转换成排序后的数组,保证展示时年份是 chronological 顺序

第二步:完整的React Native组件实现

下面是可直接复用的组件代码,包含数据处理、UI渲染和基础样式:

import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
const _ = require('lodash');

const BillDisplay = () => {
  // 你的账单数据源
  const bills = [
    {year:2021, month:5, bill:'bill in 2021 may'},
    {year:2018, month:1, bill:'bill in 2018 jan'},
    {year:2019, month:1, bill:'bill in 2019 jan'},
    {year:2018, month:2, bill:'bill in 2018 feb'},
    {year:2019, month:10,bill:'bill in 2019 oct'},
    {year:2019, month:2, bill:'bill in 2019 feb'},
    {year:2019, month:6, bill:'bill in 2019 jun'},
    {year:2020, month:11,bill:'bill in 2020 nov'}
  ];

  // 数据处理:分组 + 排序
  const groupedBills = _.mapValues(
    _.groupBy(bills, 'year'), 
    (billList) => _.sortBy(billList, 'month')
  );
  // 把年份按升序排列(如果要从新到旧,把a-b改成b-a即可)
  const sortedYears = Object.keys(groupedBills).sort((a, b) => a - b);

  return (
    <View style={styles.container}>
      {sortedYears.map(year => (
        <View key={year} style={styles.yearCard}>
          {/* 年份标题:加粗突出,加个小图标增强视觉 */}
          <Text style={styles.yearTitle}>📅 {year}</Text>
          {/* 遍历该年份下的所有账单 */}
          {groupedBills[year].map((item, idx) => (
            <Text key={`${year}-${idx}`} style={styles.billItem}>
              • {item.bill}
            </Text>
          ))}
        </View>
      ))}
    </View>
  );
};

// 基础样式:让界面更整洁美观
const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 16,
    backgroundColor: '#f8f9fa',
  },
  yearCard: {
    backgroundColor: 'white',
    padding: 14,
    borderRadius: 8,
    marginBottom: 16,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3, // 安卓端阴影效果
  },
  yearTitle: {
    fontSize: 18,
    fontWeight: '700',
    color: '#2d3748',
    marginBottom: 10,
  },
  billItem: {
    fontSize: 14,
    color: '#4a5568',
    marginVertical: 2,
    paddingLeft: 8,
  },
});

export default BillDisplay;

一些可自定义的点

  • 如果需要年份降序展示,修改sortedYears的排序逻辑:sort((a, b) => b - a)
  • 如果要按月份降序排列账单,把_.sortBy(billList, 'month')改成_.sortBy(billList, 'month').reverse()
  • 样式部分可以根据你的App主题调整颜色、字体大小、间距等

内容的提问来源于stack exchange,提问作者Mark Thien

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:55:25