MUI Datagrid:行分组,详细信息显示在同一单元格中

问题描述 投票:0回答:1

我正在使用 datagrid mui 行分组。这是代码。

const Report = () => {
  const apiRef = useGridApiRef();
  const initialState = useKeepGroupedColumnsHidden({
    apiRef,
    initialState: {
      sorting: {
        sortModel: [{ field: "__row_group_by_columns_group__", sort: "asc" }],
      },
      rowGrouping: {
        model: ["company", "vendorName"],
      },
    },
  });
  return (
        <DataGridPremium
          rows={[
            {
              id: 1,
              company: "Apple Inc.",
              vendorName: "Apple",
              unitId: "a1fsfsdfefsefsf",
              date: dayjs().format("MM/DD/YYYY"),
              lastGeneratedDate: dayjs().format("MM/DD/YYYY"),
            },
          ]}
          columns={[
            ...reportTableColumn,
            {
              field: "date",
              align: "left",
              headerName: "Date",
              headerAlign: "left",
              flex: 2,
            },
          ]}
          apiRef={apiRef}
          initialState={initialState}
        />
  );
};

现在我想要的是显示分组行本身的常见细节。看一下图片,最后生成的日期应该出现在上面。

enter image description here

javascript reactjs material-ui datagrid mui-datatable
1个回答
0
投票

要实现此目的,您需要为分组单元格定义自定义渲染函数,如下所示:

import { DataGridPremium, useGridApiRef, GridGroupNode } from '@mui/x-data-grid-premium';
import dayjs from 'dayjs'; 

const Report = () => {
  const apiRef = useGridApiRef();

  const initialState = {
    sorting: {
      sortModel: [{ field: "__row_group_by_columns_group__", sort: "asc" }],
    },
    rowGrouping: {
      model: ["company", "vendorName"],
    },
  };

  // Custom render function for group cells
  const renderGroupingCell = (params) => {
    // params.rowNode contains the group information
    const groupNode = params.rowNode as GridGroupNode;
    const { field } = params.colDef;

    if (field === '__row_group_by_columns_group__') {
     
      if (groupNode.groupingKey !== null) {
        const commonData = groupNode.children.find(child => child.type === 'data');

        if (commonData) {
          const data = commonData.row;
          return (
            <>
              <strong>{groupNode.groupingKey}</strong> - Last Generated: {data.lastGeneratedDate}
            </>
          );
        }
      }
    }

    return null;
  };

  return (
    <DataGridPremium
      rows={[
        {
          id: 1,
          company: "Apple Inc.",
          vendorName: "Apple",
          unitId: "a1fsfsdfefsefsf",
          date: dayjs().format("MM/DD/YYYY"),
          lastGeneratedDate: dayjs().format("MM/DD/YYYY"),
        },
      ]}
      columns={[
        {
          field: "company",
          headerName: "Company",
          flex: 1,
          renderGroupingCell: renderGroupingCell,
        },
      ]}
      apiRef={apiRef}
      initialState={initialState}
    />
  );
};
© www.soinside.com 2019 - 2024. All rights reserved.