跳到内容
+

数据表格 - 树形数据

使用树形数据处理具有父/子关系的行。

要启用树形数据,您只需使用 treeData 属性并提供 getTreeDataPath 属性。getTreeDataPath 函数返回一个字符串数组,表示给定行的路径。

// The following examples will both render the same tree
// - Sarah
//     - Thomas
//         - Robert
//         - Karen

const columns: GridColDef[] = [{ field: 'jobTitle', width: 250 }];

// Without transformation
const rows: GridRowsProp = [
  { path: ['Sarah'], jobTitle: 'CEO', id: 0 },
  { path: ['Sarah', 'Thomas'], jobTitle: 'Head of Sales', id: 1 },
  { path: ['Sarah', 'Thomas', 'Robert'], jobTitle: 'Sales Person', id: 2 },
  { path: ['Sarah', 'Thomas', 'Karen'], jobTitle: 'Sales Person', id: 3 },
];

const getTreeDataPath: DataGridProProps['getTreeDataPath'] = (row) => row.path;

<DataGridPro
  treeData
  getTreeDataPath={getTreeDataPath}
  rows={rows}
  columns={columns}
/>;

// With transformation
const rows: GridRowsProp = [
  { path: 'Sarah', jobTitle: 'CEO', id: 0 },
  { path: 'Sarah/Thomas', jobTitle: 'Head of Sales', id: 1 },
  { path: 'Sarah/Thomas/Robert', jobTitle: 'Sales Person', id: 2 },
  { path: 'Sarah/Thomas/Karen', jobTitle: 'Sales Person', id: 3 },
];

const getTreeDataPath: DataGridProProps['getTreeDataPath'] = (row) =>
  row.path.split('/');

<DataGridPro
  treeData
  getTreeDataPath={getTreeDataPath}
  rows={rows}
  columns={columns}
/>;

自定义分组列

行分组的行为相同,但 leafFieldmainGroupingCriteria 除外,它们不适用于树形数据。

访问分组列字段

如果您想访问分组列字段,例如,将其与列固定一起使用,可以使用 GRID_TREE_DATA_GROUPING_FIELD 常量。

<DataGridPro
  treeData
  initialState={{
    pinnedColumns: {
      left: [GRID_TREE_DATA_GROUPING_FIELD],
    },
  }}
  {...otherProps}
/>

组展开

行分组的行为相同。

自动父项和子项选择

行分组的行为相同。

树中的间隙

如果缺少某些条目来构建完整的树,Data Grid Pro 将自动创建行来填充这些间隙。

筛选

如果满足以下条件之一,则包含节点

  • 其至少一个后代通过筛选器
  • 它通过筛选器

默认情况下,筛选应用于树的每个深度。您可以使用 disableChildrenFiltering 属性将筛选限制为顶层行。

排序

默认情况下,排序应用于树的每个深度。您可以使用 disableChildrenSorting 属性将排序限制为顶层行。

子项懒加载

查看服务端树形数据部分,了解有关懒加载树形数据子项的更多信息。

完整示例