首页 > web前端 > js教程 > 正文

使用 React Router v6 在 React 中实现面包屑

Linda Hamilton
发布: 2024-09-29 06:18:01
原创
242 人浏览过

Implementing Breadcrumbs in React using React Router v6

面包屑在网页开发中非常重要,因为它们为用户提供了一种方法来跟踪他们在我们网页中的当前位置,并帮助我们的网页导航。

在本指南中,我们将使用 React-router v6 和 Bootstrap 在 React 中实现面包屑。

React-router v6 是 React 和 React Native 中使用的路由库,用于在网页或 Web 应用程序中导航。

我们的实现使用 Typescript,但它也可以轻松用于基于 Javascript 的项目。

设置

首先,如果尚未安装的话,让我们在我们的项目中安装react-router-dom:

npm 安装react-router-dom

或者替代方案,使用纱线:

纱线添加react-router-dom

让我们也安装 bootstrap 来设计我们的组件:

npm 安装引导

实现我们的组件

然后我们创建一个 Breadcrumbs.tsx 组件,它将包含面包屑的标记,还包括确定相对于根位置的当前位置的必要逻辑。

让我们首先为组件添加一个简单的标记:

 <div className='text-primary'>
   <nav aria-label='breadcrumb'>
      <ol className='breadcrumb'>
        <li className='breadcrumb-item pointer'>
          <span className='bi bi-arrow-left-short me-1'></span>
            Back
        </li>
      </ol>
   </nav>
</div>
登录后复制

该组件目前只有一个后退按钮。让我们为后退按钮添加一个简单的实现,这样当单击时,应该加载上一页:

  const goBack = () => {
    window.history.back();
  };

登录后复制

下一步将编写一个函数,该函数将使用 matchRoutes 函数来获取当前路由并应用转换来过滤出与当前路由相关的所有路由。
matchRoute 接受 AgnosticRouteObject 类型的对象数组并返回 AgnosticRouteMatch[] | null 其中 T 是我们传入的对象的类型。
另外需要注意的是,该对象必须包含名为 path 的属性。

让我们首先为我们的路线声明一个接口:

export interface IRoute {
  name: string;
  path: string; //Important
}
登录后复制

然后让我们声明我们的路线:

const routes: IRoute[] = [
  {
    path: '/home',
    name: 'Home'
  },
  {
    path: '/home/about',
    name: 'About'
  },
  {
    path: '/users',
    name: 'Users'
  },
  {
    path: '/users/:id',
    name: 'User'
  },
  {
    path: '/users/:id/settings/edit',
    name: 'Edit User Settings'
  }
];
登录后复制

我们还声明了一个变量来保存 useLocation 钩子,还声明了另一个变量来保存面包屑的状态:

const location = useLocation();
const [crumbs, setCrumbs] = useState<IRoute[]>([]);
登录后复制

接下来,让我们实现我们的功能:

const getPaths = () => {
  const allRoutes = matchRoutes(routes, location);
  const matchedRoute = allRoutes ? allRoutes[0] : null;
  let breadcrumbs: IRoute[] = [];
  if (matchedRoute) {
    breadcrumbs = routes
      .filter((x) => matchedRoute.route.path.includes(x.path))
      .map(({ path, ...rest }) => ({
        path: Object.keys(matchedRoute.params).length
          ? Object.keys(matchedRoute.params).reduce(
              (path, param) => path.replace(`:${param}`, matchedRoute.params[param] as string), path)
          : path,
        ...rest,
      }));
  }
  setCrumbs(breadcrumbs);
};
登录后复制

在这里,我们首先获取与当前位置匹配的所有路线:
const allRoutes = matchRoutes(路线, 位置);

然后我们快速检查是否返回任何结果,并选择第一个:
常量匹配路由=所有路由? allRoutes[0] : null;

接下来,我们过滤掉所有与当前路由匹配的路由:
routes.filter((x) =>matchedRoute.route.path.includes(x.path))

然后让我们使用结果创建一个新数组,检查路径是否有参数,然后用参数值交换动态路由:

 .map(({ path, ...rest }) => ({
          path: Object.keys(matchedRoute.params).length
            ? Object.keys(matchedRoute.params).reduce(
                (path, param) => path.replace(`:${param}`, matchedRoute.params[param] as string),
                path
              )
            : path,
          ...rest,
        }));
登录后复制

这确保了如果我们在路由中将路由声明为 /users/:id/edit 并将 id 传递为 1,那么我们将得到 /users/1/edit。

接下来,让我们在 useEffect 中调用我们的函数,以便它在每次我们的位置发生变化时运行:

  useEffect(() => {
    getPaths();
  }, [location]);
登录后复制

完成此操作后,我们就可以在标记中使用面包屑:

{crumbs.map((x: IRoute, key: number) =>
  crumbs.length === key + 1 ? (
    <li className='breadcrumb-item'>{x.name}</li>
      ) : (
        <li className='breadcrumb-item'>
          <Link to={x.path} className=' text-decoration-none'>
            {x.name}
          </Link>
        </li>
      )
 )}
登录后复制

在这里,显示所有的面包屑及其链接,除了最后一个仅显示名称的面包屑。

这样,我们现在就有了完整的 BreadCrumbs.tsx 组件:

import { useEffect, useState } from 'react';
import { Link, matchRoutes, useLocation } from 'react-router-dom';

export interface IRoute {
  name: string;
  path: string;
}

const routes: IRoute[] = [
  {
    path: '/home',
    name: 'Home',
  },
  {
    path: '/home/about',
    name: 'About',
  },
  {
    path: '/users',
    name: 'Users',
  },
  {
    path: '/users/:id/edit',
    name: 'Edit Users by Id',
  },
];

const Breadcrumbs = () => {
  const location = useLocation();
  const [crumbs, setCrumbs] = useState([]);

  //   const routes = [{ path: '/members/:id' }];

  const getPaths = () => {
    const allRoutes = matchRoutes(routes, location);
    const matchedRoute = allRoutes ? allRoutes[0] : null;
    let breadcrumbs: IRoute[] = [];
    if (matchedRoute) {
      breadcrumbs = routes
        .filter((x) => matchedRoute.route.path.includes(x.path))
        .map(({ path, ...rest }) => ({
          path: Object.keys(matchedRoute.params).length
            ? Object.keys(matchedRoute.params).reduce(
                (path, param) => path.replace(`:${param}`, matchedRoute.params[param] as string),
                path
              )
            : path,
          ...rest,
        }));
    }
    setCrumbs(breadcrumbs);
  };

  useEffect(() => {
    getPaths();
  }, [location]);

  const goBack = () => {
    window.history.back();
  };

  return (
    
); }; export default Breadcrumbs;
登录后复制

然后我们可以在应用程序的任何部分使用该组件,最好是在布局中。

结论

我们已经了解了如何实现一个简单的面包屑组件,我们可以将其添加到我们的应用程序中以改进导航和用户体验。

有用的链接

https://stackoverflow.com/questions/66265608/react-router-v6-get-path-pattern-for-current-route

https://medium.com/@mattywilliams/generating-an-automatic-breadcrumb-in-react-router-fed01af1fc3,这篇文章的灵感来自于此。

以上是使用 React Router v6 在 React 中实现面包屑的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!