亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

如何使用 React Router v6 在 React 中實(shí)現(xiàn)面包屑

 更新時(shí)間:2024年09月30日 11:49:14   作者:憂郁的蛋~  
面包屑在網(wǎng)頁(yè)開發(fā)中的角色不可忽視,它們?yōu)橛脩籼峁┝艘环N跟蹤其在網(wǎng)頁(yè)中當(dāng)前位置的方法,并有助于網(wǎng)頁(yè)導(dǎo)航,本文介紹了如何使用react-router v6和bootstrap在react中實(shí)現(xiàn)面包屑,感興趣的朋友一起看看吧

面包屑在網(wǎng)頁(yè)開發(fā)中非常重要,因?yàn)樗鼈優(yōu)橛脩籼峁┝艘环N跟蹤其在網(wǎng)頁(yè)中當(dāng)前位置的方法,并有助于網(wǎng)頁(yè)導(dǎo)航。

在本文中,我們將使用 react-router v6 和 bootstrap 在 react 中實(shí)現(xiàn)面包屑。

react-router v6 是 react 和 react native 中使用的路由庫(kù),用于在網(wǎng)頁(yè)或 web 應(yīng)用程序中導(dǎo)航。

我們的實(shí)現(xiàn)使用 typescript,但它也可以輕松用于基于 javascript 的項(xiàng)目。

設(shè)置

首先,如果尚未安裝的話,讓我們?cè)谖覀兊捻?xiàng)目中安裝react-router-dom:

npm 安裝react-router-dom

或者替代方案,使用紗線:

紗線添加react-router-dom

讓我們也安裝 bootstrap 來(lái)設(shè)計(jì)我們的組件:

npm 安裝引導(dǎo)

實(shí)現(xiàn)我們的組件

然后我們創(chuàng)建一個(gè) breadcrumbs.tsx 組件,它將包含面包屑的標(biāo)記,還包括確定相對(duì)于根位置的當(dāng)前位置的必要邏輯。

讓我們首先為組件添加一個(gè)簡(jiǎn)單的標(biāo)記:

<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>

該組件目前只有一個(gè)后退按鈕。讓我們?yōu)楹笸税粹o添加一個(gè)簡(jiǎn)單的實(shí)現(xiàn),這樣當(dāng)單擊時(shí),應(yīng)該加載上一頁(yè):

const goback = () =&gt; {
    window.history.back();
  };

下一步將編寫一個(gè)函數(shù),該函數(shù)將使用 matchroutes 函數(shù)來(lái)獲取當(dāng)前路由并應(yīng)用轉(zhuǎn)換來(lái)過(guò)濾出與當(dāng)前路由相關(guān)的所有路由。
matchroute 接受 agnosticrouteobject 類型的對(duì)象數(shù)組并返回 agnosticroutematch[] | null 其中 t 是我們傳入的對(duì)象的類型。
另外需要注意的是,該對(duì)象必須包含名為 path 的屬性。

讓我們首先為我們的路線聲明一個(gè)接口:

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'
  }
];

我們還聲明了一個(gè)變量來(lái)保存 uselocation 鉤子,還聲明了另一個(gè)變量來(lái)保存面包屑的狀態(tài):

const location = uselocation();
const [crumbs, setcrumbs] = usestate<iroute>([]);
</iroute>

接下來(lái),讓我們實(shí)現(xiàn)我們的功能:

const getpaths = () =&gt; {
  const allroutes = matchroutes(routes, location);
  const matchedroute = allroutes ? allroutes[0] : null;
  let breadcrumbs: iroute[] = [];
  if (matchedroute) {
    breadcrumbs = routes
      .filter((x) =&gt; matchedroute.route.path.includes(x.path))
      .map(({ path, ...rest }) =&gt; ({
        path: object.keys(matchedroute.params).length
          ? object.keys(matchedroute.params).reduce(
              (path, param) =&gt; path.replace(`:${param}`, matchedroute.params[param] as string), path)
          : path,
        ...rest,
      }));
  }
  setcrumbs(breadcrumbs);
};

在這里,我們首先獲取與當(dāng)前位置匹配的所有路線:
const allroutes = matchroutes(路線, 位置);

然后我們快速檢查是否返回任何結(jié)果,并選擇第一個(gè):
常量匹配路由=所有路由? allroutes[0] : null;

接下來(lái),我們過(guò)濾掉所有與當(dāng)前路由匹配的路由:
routes.filter((x) =>matchedroute.route.path.includes(x.path))

然后讓我們使用結(jié)果創(chuàng)建一個(gè)新數(shù)組,檢查路徑是否有參數(shù),然后用參數(shù)值交換動(dòng)態(tài)路由:

.map(({ path, ...rest }) =&gt; ({
          path: object.keys(matchedroute.params).length
            ? object.keys(matchedroute.params).reduce(
                (path, param) =&gt; path.replace(`:${param}`, matchedroute.params[param] as string),
                path
              )
            : path,
          ...rest,
        }));

這確保了如果我們?cè)诼酚芍袑⒙酚陕暶鳛?/users/:id/edit 并將 id 傳遞為 1,那么我們將得到 /users/1/edit。

接下來(lái),讓我們?cè)?useeffect 中調(diào)用我們的函數(shù),以便每次我們的位置發(fā)生變化時(shí)它都會(huì)運(yùn)行:

useeffect(() =&gt; {
    getpaths();
  }, [location]);

完成此操作后,我們就可以在標(biāo)記中使用面包屑:

{crumbs.map((x: iroute, key: number) =&gt;
  crumbs.length === key + 1 ? ({x.name}
) : (
{x.name}
) )} 

在這里,顯示所有的面包屑及其鏈接,除了最后一個(gè)僅顯示名稱的面包屑。

這樣,我們現(xiàn)在就有了完整的 breadcrumbs.tsx 組件:

import { useEffect, useState } from 'react';
import { Link, matchRoutes, useLocation } from 'react-router-dom';
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 = () =&gt; {
  const location = useLocation();
  const [crumbs, setCrumbs] = useState<iroute>([]);
  const getPaths = () =&gt; {
    const allRoutes = matchRoutes(routes, location);
    const matchedRoute = allRoutes ? allRoutes[0] : null;
    let breadcrumbs: IRoute[] = [];
    if (matchedRoute) {
      breadcrumbs = routes
        .filter((x) =&gt; matchedRoute.route.path.includes(x.path))
        .map(({ path, ...rest }) =&gt; ({
          path: Object.keys(matchedRoute.params).length
            ? Object.keys(matchedRoute.params).reduce(
                (path, param) =&gt; path.replace(`:${param}`, matchedRoute.params[param] as string),
                path
              )
            : path,
          ...rest,
        }));
    }
    setCrumbs(breadcrumbs);
  };
  useEffect(() =&gt; {
    getPaths();
  }, [location]);
  const goBack = () =&gt; {
    window.history.back();
  };
  return (
    <div classname="">
      <nav aria-label="breadcrumb"><ol classname="breadcrumb">
<li classname="breadcrumb-item pointer" onclick="{goBack}">
            <span classname="bi bi-arrow-left-short me-1"></span>
            Back
          </li>
          {crumbs.map((x: IRoute, key: number) =&gt;
            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}
              </li>
            )
          )}
        </ol></nav>
</div>
  );
};
export default Breadcrumbs;
</iroute>

然后我們可以在應(yīng)用程序的任何部分使用該組件,最好是在布局中。

結(jié)論

我們已經(jīng)了解了如何實(shí)現(xiàn)一個(gè)簡(jiǎn)單的面包屑組件,我們可以將其添加到我們的應(yīng)用程序中以改進(jìn)導(dǎo)航和用戶體驗(yàn)。

有用的鏈接

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,這篇文章的靈感來(lái)自于此。

到此這篇關(guān)于使用 React Router v6 在 React 中實(shí)現(xiàn)面包屑的文章就介紹到這了,更多相關(guān)React面包屑內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • React18系列commit從0實(shí)現(xiàn)源碼解析

    React18系列commit從0實(shí)現(xiàn)源碼解析

    這篇文章主要為大家介紹了React18系列commit從0實(shí)現(xiàn)源碼解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-01-01
  • react事件對(duì)象無(wú)法獲取offsetLeft,offsetTop,X,Y等元素問(wèn)題及解決

    react事件對(duì)象無(wú)法獲取offsetLeft,offsetTop,X,Y等元素問(wèn)題及解決

    這篇文章主要介紹了react事件對(duì)象無(wú)法獲取offsetLeft,offsetTop,X,Y等元素問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。
    2022-08-08
  • react lazyLoad加載使用詳解

    react lazyLoad加載使用詳解

    lazy是React提供的懶(動(dòng)態(tài))加載組件的方法,React.lazy(),路由組件代碼會(huì)被分開打包,能減少打包體積、延遲加載首屏不需要渲染的組件,依賴內(nèi)置組件Suspense標(biāo)簽的fallback屬性,給lazy加上loading指示器組件,Suspense目前只和lazy配合實(shí)現(xiàn)組件等待加載指示器的功能
    2023-03-03
  • react腳手架構(gòu)建運(yùn)行時(shí)報(bào)錯(cuò)問(wèn)題及解決

    react腳手架構(gòu)建運(yùn)行時(shí)報(bào)錯(cuò)問(wèn)題及解決

    這篇文章主要介紹了react腳手架構(gòu)建運(yùn)行時(shí)報(bào)錯(cuò)問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-03-03
  • React函數(shù)組件和類組件的區(qū)別及說(shuō)明

    React函數(shù)組件和類組件的區(qū)別及說(shuō)明

    這篇文章主要介紹了React函數(shù)組件和類組件的區(qū)別及說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-08-08
  • React觸發(fā)render的實(shí)現(xiàn)方法

    React觸發(fā)render的實(shí)現(xiàn)方法

    這篇文章主要介紹了React觸發(fā)render的實(shí)現(xiàn)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-10-10
  • React自定義Hook-useForkRef的具體使用

    React自定義Hook-useForkRef的具體使用

    本文主要介紹了React自定義Hook-useForkRef的具體使用,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-03-03
  • React組件的解耦技巧分享

    React組件的解耦技巧分享

    本文我們將和大家一起來(lái)研究如何有效地將組件解耦,讓我們的代碼變的復(fù)用性極高,文中通過(guò)代碼示例講解的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下
    2023-11-11
  • react數(shù)據(jù)管理機(jī)制React.Context源碼解析

    react數(shù)據(jù)管理機(jī)制React.Context源碼解析

    這篇文章主要為大家介紹了react數(shù)據(jù)管理機(jī)制React.Context源碼解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-11-11
  • 詳解React自定義Hook

    詳解React自定義Hook

    在React項(xiàng)目中,我們經(jīng)常會(huì)使用到React自帶的幾個(gè)內(nèi)置Hooks,如 useState,useContext和useEffect。雖然在React中找不到這些 Hooks,但React提供了非常靈活的方式讓你為自己的需求來(lái)創(chuàng)建自己的自定義Hooks,想了解更多的,歡迎閱讀本文
    2023-04-04

最新評(píng)論