react+antdesign达成后台管理系统面包屑

在这里插入图片描述
andDesign面包屑组件,实现这个功能主要是当我点击对应目录下的子菜单使用递归获取当前叶子节点的最高父节点拿到整个对象塞到集合中去

创建 Breadcrumb组件

import { Breadcrumb
} from 'antd';
import { routes
} from '@/router/routes';
import { useLocation
} from'react-router-dom';
import { getBreadcrumbList
} from '@/utils';
const BreadcrumbNav = () =>
{
const location = useLocation();
const items = getBreadcrumbList(routes, location.pathname);
const breadcrumbItems = items.map(item =>
{
const childrenMenu = item.children?.map(child =>
({
key: child.path,
label: <a href={
`#${child.path
}`
}>
{child.meta.title
}<
/a>
})) || [];
return {
title: (
<span>
  {item?.meta?.title
  }<
  /span>
  ),
  menu: childrenMenu.length >
  0 ? { items: childrenMenu
  } : undefined
  };
  });
  return (
  <Breadcrumb
  items={
  [
  {
  title: <a href="#/">首页<
    /a>
    },
    ...breadcrumbItems
    ]
    }
    />
    )
    };
    export default BreadcrumbNav;

utils文件

export const searchRoute = (path: string, routes: RouteObject[] = []): RouteObject =>
{
let result: RouteObject = {
};
for (const item of routes) {
if (item.path === path) return item;
if (item.children) {
const res = searchRoute(path, item.children);
if (Object.keys(res).length) result = res;
}
}
return result;
};
export const getBreadcrumbList = (routes: RouteObject[] = [], currentPath: string) =>
{
if(!currentPath || currentPath === '/') return [];
const currentParent = findBreadcrumb(routes, currentPath)
const current = searchRoute(currentPath, routes)
return [
currentParent,
current
]
}
export const findBreadcrumb = (routes: RouteObject[] = [], targetPath: string): any =>
{
// 用于存储找到的最外层父节点
let outermostParent = null;
// 递归遍历路由配置的函数
function traverse(nodes, currentParent?: any) {
for (const node of nodes) {
// 如果当前节点有子节点,继续递归遍历
if (node.children && node.children.length >
0) {
// 检查当前节点的子节点中是否包含目标路径
const hasTarget = node.children.some(child => child.path === targetPath);
// 如果找到目标路径,记录当前节点作为父节点
if (hasTarget) {
// 最外层父节点是首次找到的包含目标路径的祖先节点
if (!outermostParent) {
outermostParent = node;
}
} else {
// 否则继续深入查找,当前节点作为临时父节点
traverse(node.children, node);
}
}
}
}
// 从根节点开始遍历
traverse(routes, null);
return outermostParent;
};
posted @ 2025-09-22 19:42  yxysuanfa  阅读(7)  评论(0)    收藏  举报