需求1
左边的Tree树形控件与右边的Breadcrumb面包屑相结合(antd)
数据结构
const mockTreeData: TreeData[] = [
{
key: "0-0",
title: "全部部门",
icon: <FolderOpenTwoTone />,
children: [
{
key: "0-0-0",
title: "部门1",
icon: <FolderOpenTwoTone />,
children: [
{
key: "0-0-0-0",
title: "部门1-1",
},
],
},
{
key: "0-0-1",
title: "部门2",
icon: <FolderOpenTwoTone />,
children: [
{
key: "0-0-1-0",
title: "部门2-1",
},
],
},
{
key: "0-0-2",
title: "部门3",
icon: <FolderOpenTwoTone />,
children: [
{
key: "0-0-2-0",
title: "部门3-1",
},
],
},
{
key: "0-0-3",
title: "部门4",
icon: <FolderOpenTwoTone />,
children: [
{
key: "0-0-3-0",
title: "部门4-1",
},
],
},
],
},
];
复制代码
解题思路
每次点击tree可得到具体的key,如:0-0-0-0
1、遍历树结构,存在children则递归便利,同时将当前的父级对象保存到数组
2、直到条件符合时候,即可得出所有的父级对象
// key: 每次点击的具体key data:数据源 treeItem: 空数组用于保存所有父级
const fullParentPath = (key: string, data: TreeData[], treeItem: TreeData[]) => {
for (let i = 0; i < data.length; i++) {
const temp = data[i];
if (key === temp.key) {
setBreadcrumbItem([...treeItem, temp]);
return;
}
if (temp.children) {
fullParentPath(key, temp.children, [...treeItem, temp]);
}
}
};
// 使用
fullParentPath('0-0-0', mockTreeData, []);
复制代码
需求2
将后端返回的数据映射成自己想要的数据
后端:
"childList": [{
"id": 1,
"deptName": "部门1",
"description": "afsdf",
"parentId": 0,
"isLeaf": false,
"childList": [{
"id": 4,
"deptName": "部门1-1",
"description": "asdf",
"parentId": 1,
"isLeaf": false,
"childList": [{
"id": 8,
"deptName": "部门1-1-1",
"description": "fefe",
"parentId": 4,
"isLeaf": true,
"childList": null
}]
}]
},
{
"id": 2,
"deptName": "部门2",
"description": "fefe",
"parentId": 0,
"isLeaf": false,
"childList": [{
"id": 5,
"deptName": "部门2-1",
"description": "fasdf",
"parentId": 2,
"isLeaf": true,
"childList": null
}]
},
{
"id": 3,
"deptName": "部门3",
"description": "fasdf",
"parentId": 0,
"isLeaf": false,
"childList": [{
"id": 6,
"deptName": "部门3-1",
"description": "fasdf",
"parentId": 3,
"isLeaf": true,
"childList": null
},
{
"id": 7,
"deptName": "部门3-2",
"description": "fefe",
"parentId": 3,
"isLeaf": false,
"childList": [{
"id": 9,
"deptName": "部门3-2-1",
"description": "asdfsa",
"parentId": 7,
"isLeaf": true,
"childList": null
}]
}]
}]
复制代码
前端:
{
key: "0-0-0",
title: "部门1",
icon: <FolderOpenTwoTone />,
children: [
{
key: "0-0-0-0",
title: "部门1-1",
},
],
}
复制代码
解法
// childList数据源
const backTrack = (childList) => {
return childList.map(({ id, deptName, childList, ...args }) => {
return {
key: id,
title: deptName,
icon: childList ? <FolderOpenTwoTone /> : null,
children: childList == null ? null : backTrack(childList),
...args,
};
});
};
复制代码
文献
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END