Material UI TreeView:在树视图中显示来自节点的多列数据

Material UI TreeView: Display multiple columns data from node in treeview

const treeItems = [
    {
        id: 1,
        name: 'English',
        country: 'US',
        children: [
            {
                id: 4,
                name: 'Spring',
                country: 'Uk',
                children: []
            }
        ]
    },
    {
        id: 14,
        name: 'Italian',
        country: 'AUS',
        children: [
            {
                id: 24,
                name: 'Level A',
                country: 'IND',
                children: []
            }
        ]
    }
]

我有树格式的数据,它可以是分层的或平面的,所以我使用了树视图。但我还想在树视图内的 table 视图中显示节点内的所有列,即 ID、名称和国家/地区。

我正在使用来自 material UI 的 Treeview 我也检查了文档。我还没有找到任何解决方案。

下面是我要显示的格式

ID                Name            Country
------------------------------------------
1                 English         US
    4                SPring         Uk
14                Italian         Aus
   24                Level A        IND

解决方案比 MUI TreeView example 稍微棘手一点。虽然示例接受数据为 JSON,但在您的情况下,您有一个 JSON.

数组

假设你想在树视图标签中显示 name 属性,你可以这样写:

<TreeView
  className={classes.root}
  defaultCollapseIcon={<ExpandMoreIcon />}
  defaultExpanded={["root"]}
  defaultExpandIcon={<ChevronRightIcon />}
>
  {renderTree(data)} //<-- this is the function that recursively inspects your array
</TreeView>

然后renderTree函数:

const renderTree = (nodes) => {
return nodes.map((el) => { //<-- mapping on array
  return (
    <TreeItem key={el.id} nodeId={el.id.toString()} label={el.id + " " + el.name + " " + el.country}>
      {Array.isArray(el.children) && el.children.length > 0
        ? renderTree(el.children) //<-- recursion in case children has values
        : null}
    </TreeItem>
  );
});
};

结果是:

Here 一个工作示例。