- Material UI 简介
 - Material UI 组件库详解
 - 使用 Material UI 的 Autocomplete 组件详解
 - 使用 Material UI 的 Button 组件详解
 - 使用 Material UI 创建按钮组(Button Group)的详细指南
 - 使用 Material UI 创建复选框(Checkbox)的详细指南
 - Material UI 中 Floating Action Button 的使用详解
 - Material UI 中 Radio Group 的使用详解
 - Material UI 中 Rating 组件的使用详解
 - Material UI 中 Select 组件的使用详解
 - Material UI 中 Slider 组件的使用详解
 - Material UI Switch 组件使用详解
 - Material UI Text Field 组件使用详解
 - Material UI Transfer List 使用详解
 - Material UI Toggle Button 使用详解
 - Material UI Avatar 组件使用详解
 - Material UI Badge 组件使用详解
 - Material UI Chip 组件使用详解
 - Material UI Divider 组件使用详解
 - Material UI Icons 组件使用详解
 - Material UI 中 Material Icons 的使用详解
 - Material UI 框架中 Lists 的使用详解
 - Material UI 框架中 Table 的使用详解
 - Material UI 框架中 Tooltip 的使用详解
 - Material UI 框架中 Typography 的使用详解
 - Material UI 框架中 Alert 组件的使用详解
 - Material UI 框架中 Backdrop 组件的详细使用教程
 - Material UI 框架中 Dialog 组件的详细使用教程
 - Material UI Progress 组件详解及示例
 - Material UI 框架中的 Skeleton 组件详解
 - Material UI 框架中的 Snackbar 组件详解
 - Material UI 框架中的 Accordion 组件详解
 - Material UI 框架中的 App Bar 组件详解
 - Material UI 框架中的 Card 组件详解
 - Material UI 框架中的 Paper 组件详解
 - 使用 Material UI 框架中的 Bottom Navigation 组件
 - 使用 Material UI 框架中的 Breadcrumbs 组件
 - 使用 Material UI 框架中的 Drawer 组件
 - 使用 Material UI 框架中的 Links 组件
 - 使用 Material UI 框架中的 Menu 组件
 - 使用 Material UI 框架中的 Pagination 组件
 - 使用 Material UI 框架中的 Speed Dial 组件
 - 使用 Material UI 框架中的 Stepper 组件
 - 使用 Material UI 框架中的 Tabs 组件
 - 使用 Material UI 框架中的 Layout Box 组件
 - 使用 Material UI 框架中的 Layout Container
 - 使用 Material UI 框架中的 Layout Grid
 - 使用 Material UI 框架中的 Layout Grid Version 2
 - 使用 Material UI 框架中的 Layout Stack
 - 使用 Material UI 框架中的 Layout Image List
 - 使用 Material UI 框架中的 Layout Hidden
 - 使用 Material UI 框架中的 Click-Away Listener
 - 使用 Material UI 框架中的 CSS Baseline
 - 使用 Material UI 框架中的 Utils Modal
 - 使用 Material UI 框架中的 Utils No SSR
 - 使用 Material UI 框架中的 Utils Popover
 - 使用 Material UI 框架中的 Utils Popper
 - 使用 Material UI 框架中的 Utils Portal
 - 使用 Material UI 框架中的 Utils Textarea Autosize
 - 使用 Material UI 框架中的 Utils Transitions
 - 使用 Material UI 框架中的 `useMediaQuery`
 - 使用 Material UI 框架中的 MUI X Data Grid
 - 使用 Material UI 框架中的 Data Grid - Layout
 - 使用 Material UI 框架中的 Data Grid:深入探索列定义与管理
 - 深入探索 Material UI 框架中的 Data Grid:行定义与管理
 - 深入探索 Material UI 框架中的 Data Grid 编辑功能
 - 深入探索 Material UI 框架中的 Data Grid 排序功能
 - 深入探索 Material UI 框架中的 Data Grid 过滤功能
 - 深入探索 Material UI 框架中的 Data Grid 分页功能
 - 深入探索 Material UI 框架中的 Data Grid 行选择和单元格选择功能
 - 深入探索 Material UI 框架中的 Data Grid 导出功能
 - 深入探索 Material UI 框架中的 Data Grid - Copy and Paste 功能
 - 深入探索 Material UI 框架中的 Data Grid - Overlays 功能
 - 深入探索 Material UI 框架中的 Data Grid - Custom Slots and Subcomponents
 - 深入探索 Material UI 框架中的 Data Grid - Styling 和 Styling Recipes
 - 深入探索 Material UI 框架中的 Data Grid - Translated Components
 - 使用 Material UI 的 Data Grid - Scrolling 功能
 - 使用 Material UI 的 Data Grid - Virtualization 功能
 - 使用 Material UI 的 Data Grid - 可访问性(Accessibility)功能
 - 使用 Material UI 的 Data Grid - 性能(Performance)优化
 - 使用 Material UI 的 Data Grid - 树形数据(Tree Data)
 - 使用 Material UI 的 Data Grid - 行分组(Row Grouping)
 - 使用 Material UI 的 Data Grid - 数据聚合(Aggregation)
 - 使用 Material UI 的 Data Grid - 数据透视(Pivoting)
 - 使用 Material UI 的 Data Grid - 服务器端数据(Server-side Data)
 - 使用 Material UI 的 Data Grid - 服务器端树形数据(Server-side Tree Data)
 - 使用 Material UI 的 Data Grid - 服务器端懒加载(Server-side Lazy Loading)
 - 使用 Material UI 的 Data Grid - 服务器端行分组(Server-side Row Grouping)
 - 使用 Material UI 的 Data Grid - 服务器端聚合(Server-side Aggregation)
 - 使用 Material UI 的 Data Grid - API Object
 - 使用 Material UI 的 Data Grid - 事件处理(Events)
 - 使用 Material UI 的 Data Grid - State 管理
 - Material UI Data Grid - 编辑功能详解与使用示例
 - Material UI Data Grid - Row Grouping 使用指南与示例
 - Material UI DataGrid API 使用指南
 - Material UI DataGridPremium API 使用指南
 - Material UI 框架 DataGridPro API 使用指南
 - Material UI 框架 GridFilterForm API 使用指南
 - Material UI 框架 GridFilterPanel API 使用指南
 - Material UI 框架 GridApi API 使用指南
 - Material UI 框架 GridCellParams API 使用指南
 - Material UI 框架 GridColDef API 使用指南
 - Material UI 框架 GridSingleSelectColDef API 使用指南
 - Material UI 框架 GridActionsColDef API 使用指南
 - Material UI 框架 GridExportStateParams API 使用指南
 - Material UI 框架 GridFilterItem API 使用指南
 - Material UI 框架 GridFilterModel API 使用指南
 - Material UI 框架:GridToolbarQuickFilter API 使用详解
 - Material UI 框架:GridApi 接口详解及其使用
 - Material UI 框架:Interface `GridCellParams` API 使用详解
 - Material UI 框架:Interface `GridColDef` API 使用详解
 - Material UI 框架:Interface `GridSingleSelectColDef` API 使用详解
 - Material UI 框架:Interface `GridActionsColDef` API 使用详解
 - Material UI 框架:Interface `GridExportStateParams` API 使用详解
 - Material UI 框架:`GridFilterItem` API 使用详解
 - Material UI 框架:`GridFilterModel` API 使用详解
 - Material UI 框架:`Interface GridFilterOperator` API 使用详解
 - Material UI 框架:`GridRowClassNameParams` 接口详解及使用指南
 - Material UI 框架:`GridRowParams` 接口详解及使用指南
 - Material UI 框架:`GridRowSpacingParams` 接口详解及使用指南
 - Material UI 框架:`GridAggregationFunction` 接口详解及使用指南
 - Material UI 框架:`GridCsvExportOptions` 接口详解及使用指南
 - Material UI 框架:`GridPrintExportOptions` 接口详解及使用指南
 - Material UI 框架:`GridExcelExportOptions` 接口详解及使用指南
 - Material UI 框架:MUI X 日期和时间选择器使用指南
 - Material UI 框架:日期和时间选择器 - 入门指南
 - Material UI 框架:日期和时间选择器 - 基本概念
 - Material UI 框架:日期和时间选择器 - 可访问性
 - Material UI 框架之 Date Picker 组件详解
 - Material UI 框架之 Date Field 组件详解
 - Material UI 框架之 Date Calendar 组件详解
 - Material UI 框架之 Time Picker 组件详解
 - Material UI 框架之 Time Field 组件详解
 - Material UI 框架之 Time Clock 组件详解
 - Material UI 框架之 Digital Clock 组件详解
 - Material UI 框架之 DateTime Picker 组件详解
 - Material UI 框架之 DateTime Field 组件详解
 - Material UI 组件 Date Range Picker 使用详解
 - Material UI 组件 Date Range Field 使用详解
 - Material UI 组件 Date Range Calendar 使用详解
 - Material UI 组件 Time Range Picker 使用详解
 - Material UI 组件 Time Range Field 使用详解
 - Material UI 组件 Date Time Range Picker 使用详解
 - Material UI 组件 Date Time Range Field 使用详解
 - 使用 Material-UI 的 Fields 组件详解
 - 使用 Material-UI 的 DateCalendar 组件详解
 - 使用 Material-UI 的 DateField 组件详解
 - 使用 Material-UI 的 DatePicker 组件详解
 - 使用 Material-UI 的 DatePickerToolbar API 详解
 - 使用 Material-UI 的 DateRangeCalendar API 详解
 - 使用 Material-UI 的 DateRangePicker API 详解
 - 使用 Material-UI 的 DateRangePickerDay API 详解
 - 使用 Material UI DateRangePickerToolbar API 详解
 - 深入了解 Material UI DateTimeField API 使用
 - 深入了解 Material UI DateTimePicker API 使用
 - 深入了解 Material UI `DateTimePickerTabs` API 的使用
 - 深入了解 Material UI 框架中的 `DateTimePickerToolbar` API
 - 深入了解 Material UI 框架中的 `DateTimeRangePicker` API
 - Material UI 框架中的 DateTimeRangePickerTabs API 使用详解
 - 深入了解 Material UI 框架中的 `DateTimeRangePickerToolbar API`
 - 深入了解 Material UI 框架中的 `DayCalendarSkeleton API`
 - 深入解析 Material UI 的 DesktopDatePicker API 使用指南
 - 深入解析 Material UI 的 `DesktopDateRangePicker API` 使用指南
 - 深入解析 Material UI 的 `DesktopDateTimePicker API` 使用指南
 - 深入解析 Material UI 的 `DesktopDateTimeRangePicker API` 使用指南
 - 深入解析 Material UI 的 `DesktopTimePicker API` 使用指南
 - 深入解析 Material UI 的 `DigitalClock API` 使用指南
 - 深入解析 Material UI 的 `LocalizationProvider API` 使用指南
 - Material UI 框架中 MobileDatePicker API 的全面使用指南
 - 深入了解 Material UI 的 MobileDateRangePicker API 使用
 
使用 Material UI 的 Data Grid - 数据聚合(Aggregation)
class 数据聚合,Aggregation数据聚合是一种强大的功能,可以帮助用户快速分析和总结大量数据。在 Material UI 的 Data Grid 组件中,聚合功能使得在表格中汇总数据变得更加直观。本文将详细介绍如何使用 Data Grid 的数据聚合功能,包括所有相关属性和方法,并结合其他组件提供丰富的示例代码。
1. 安装 Material UI 和 Data Grid
在开始之前,确保你已安装 Material UI 和 Data Grid。可以使用以下命令进行安装:
npm install @mui/material @mui/x-data-grid
同时还需要安装 @mui/icons-material,以便使用图标。
npm install @mui/icons-material
2. 数据聚合的基本用法
2.1 数据结构
首先,我们需要准备一组数据。在此示例中,我们将使用销售数据,包括产品类别、产品名称和销售额等信息。
const rows = [
  { id: 1, category: 'Electronics', product: 'Smartphone', sales: 200 },
  { id: 2, category: 'Electronics', product: 'Laptop', sales: 500 },
  { id: 3, category: 'Home Appliances', product: 'Refrigerator', sales: 300 },
  { id: 4, category: 'Home Appliances', product: 'Washing Machine', sales: 400 },
  { id: 5, category: 'Furniture', product: 'Sofa', sales: 700 },
  { id: 6, category: 'Furniture', product: 'Table', sales: 200 },
];
2.2 列定义
接下来,我们定义列,以便在 Data Grid 中显示我们的数据。这里我们将定义类别、产品和销售额列。
const columns = [
  { field: 'category', headerName: 'Category', flex: 1 },
  { field: 'product', headerName: 'Product', flex: 1 },
  { field: 'sales', headerName: 'Sales', type: 'number', flex: 1 },
];
3. 使用 Data Grid 实现数据聚合
3.1 启用聚合功能
要实现聚合功能,我们可以通过 getRowId 方法自定义每行的唯一标识,并使用 groupBy 属性启用分组。我们可以计算每组的总销售额等聚合值。
import React from 'react';
import { DataGrid } from '@mui/x-data-grid';
const AggregatedDataGrid = () => {
  return (
    <div style={{ height: 400, width: '100%' }}>
      <DataGrid
        rows={rows}
        columns={columns}
        pageSize={5}
        rowsPerPageOptions={[5]}
        groupBy={['category']}
        getRowId={(row) => row.id}
        getRowClassName={(params) =>
          params.row.product === 'Total' ? 'total-row' : ''
        }
      />
    </div>
  );
};
export default AggregatedDataGrid;
在这个示例中,我们启用了按类别分组(groupBy)并为每一组的销售额计算了总和。
3.2 自定义聚合函数
为了计算不同类型的聚合,我们可以自定义聚合函数。例如,可以计算每个类别的总销售额和平均销售额。
const calculateAggregates = (rows) => {
  const aggregates = {};
  
  rows.forEach((row) => {
    if (!aggregates[row.category]) {
      aggregates[row.category] = { total: 0, count: 0 };
    }
    aggregates[row.category].total += row.sales;
    aggregates[row.category].count += 1;
  });
  return Object.entries(aggregates).map(([key, value]) => ({
    id: key,
    category: key,
    product: 'Total',
    sales: value.total,
    average: value.total / value.count,
  }));
};
const AggregatedDataGrid = () => {
  const aggregatedRows = calculateAggregates(rows);
  return (
    <div style={{ height: 400, width: '100%' }}>
      <DataGrid
        rows={[...rows, ...aggregatedRows]} // 合并原始数据和聚合数据
        columns={columns}
        pageSize={5}
        rowsPerPageOptions={[5]}
      />
    </div>
  );
};
在这个示例中,我们计算了每个类别的总销售额和平均销售额,并将其显示在 Data Grid 中。
4. 结合其他组件使用
4.1 添加筛选功能
在使用数据聚合的同时,我们可以添加筛选功能,以便用户能够快速找到感兴趣的数据。可以结合 Material UI 的 TextField 组件实现筛选。
import React, { useState } from 'react';
import { DataGrid } from '@mui/x-data-grid';
import TextField from '@mui/material/TextField';
const FilteredAggregatedDataGrid = () => {
  const [filterText, setFilterText] = useState('');
  const filteredRows = rows.filter((row) =>
    row.product.toLowerCase().includes(filterText.toLowerCase())
  );
  const aggregatedRows = calculateAggregates(filteredRows);
  return (
    <div style={{ height: 400, width: '100%' }}>
      <TextField
        label="Filter by Product"
        variant="outlined"
        onChange={(e) => setFilterText(e.target.value)}
        style={{ marginBottom: '16px' }}
      />
      <DataGrid
        rows={[...filteredRows, ...aggregatedRows]} // 合并筛选后的数据和聚合数据
        columns={columns}
        pageSize={5}
        rowsPerPageOptions={[5]}
      />
    </div>
  );
};
export default FilteredAggregatedDataGrid;
在这个示例中,我们使用 TextField 组件提供了筛选功能,允许用户根据产品名称过滤显示的行。
4.2 显示聚合摘要
可以在表格下方显示聚合摘要,帮助用户快速了解数据。
const calculateTotalSales = (rows) => {
  return rows.reduce((total, row) => total + row.sales, 0);
};
const FilteredAggregatedDataGrid = () => {
  const [filterText, setFilterText] = useState('');
  const filteredRows = rows.filter((row) =>
    row.product.toLowerCase().includes(filterText.toLowerCase())
  );
  const totalSales = calculateTotalSales(filteredRows);
  return (
    <div style={{ height: 400, width: '100%' }}>
      <TextField
        label="Filter by Product"
        variant="outlined"
        onChange={(e) => setFilterText(e.target.value)}
        style={{ marginBottom: '16px' }}
      />
      <DataGrid
        rows={filteredRows}
        columns={columns}
        pageSize={5}
        rowsPerPageOptions={[5]}
      />
      <div>Total Sales: {totalSales}</div>
    </div>
  );
};
在这个示例中,我们计算了筛选后的总销售额,并在表格下方显示。
5. 属性和方法总结
5.1 主要属性
- rows: 数据源,数组格式。
 - columns: 列定义,数组格式。
 - groupBy: 启用分组的列。
 - pageSize: 每页显示的行数。
 - rowsPerPageOptions: 可选择的每页行数选项。
 - getRowId: 自定义每行的唯一标识。
 
5.2 主要方法
- calculateAggregates: 自定义聚合计算方法。
 - calculateTotalSales: 计算总销售额的方法。
 
6. 完整示例
以下是结合所有功能的完整示例代码:
import React, { useState } from 'react';
import { DataGrid } from '@mui/x-data-grid';
import TextField from '@mui/material/TextField';
const rows = [
  { id: 1, category: 'Electronics', product: 'Smartphone', sales: 200 },
  { id: 2, category: 'Electronics', product: 'Laptop', sales: 500 },
  { id: 3, category: 'Home Appliances', product: 'Refrigerator', sales: 300 },
  { id: 4, category: 'Home Appliances', product: 'Washing Machine', sales: 400 },
  { id: 5, category: 'Furniture', product: 'Sofa', sales: 700 },
  { id: 6, category: 'Furniture', product: 'Table', sales: 200 },
];
const columns = [
  { field: 'category', headerName: 'Category', flex: 1 },
  { field: 'product', headerName: 'Product', flex: 1 },
  { field: 'sales', headerName: 'Sales', type: 'number', flex: 1 },
];
const calculateAggregates = (rows) => {
  const aggregates = {};
  
  rows.forEach((row) => {
    if (!aggregates[row.category]) {
      aggregates[row.category] = { total: 0, count: 0 };
    }
    aggregates[row.category].total += row.sales;
    aggregates[row.category].count += 1;
  });
  return Object.entries(aggregates).map(([key, value]) => ({
    id: key,
    category: key,
    product: 'Total',
    sales: value.total,
    average: value.total / value.count,
  }));
};
const FilteredAggregatedDataGrid = () => {
  const [filterText, setFilterText] = useState('');
  const filteredRows = rows.filter((row) =>
    row.product.toLowerCase().includes(filterText.toLowerCase())
  );
  const aggregatedRows = calculateAggregates(filteredRows);
  const totalSales = calculateTotalSales(filteredRows);
  return (
    <div style={{ height: 400, width: '100%' }}>
      <TextField
        label="Filter by Product"
        variant="outlined"
        onChange={(e) => setFilterText(e.target.value)}
        style={{ marginBottom: '16px' }}
      />
      <DataGrid
        rows={[...filteredRows, ...aggregatedRows]} // 合并筛选后的数据和聚合数据
        columns={columns}
        pageSize={5}
        rowsPerPageOptions={[5]}
      />
      <div>Total Sales: {totalSales}</div>
    </div>
  );
};
export default FilteredAggregatedDataGrid;
结论
Material UI 的 Data Grid 组件通过数据聚合功能使得数据的分析和总结变得更加高效。在本文中,我们探讨了如何设置聚合、定制聚合计算、结合筛选功能以及显示聚合摘要等。希望本文能帮助你更好地理解和使用 Data Grid 的聚合功能,提升你的应用程序的用户体验。