ant-design/components/breadcrumb/demo/react-router.md
章鱼 7fd093bd0a
docs: feat components TS demo (#34742)
* docs: add general components TS demo

* docs: add layout components TS demo

* docs: add navigation components TS demo

* docs: add data entry components TS demo

* chore(deps): add types for qs

* docs: add data display TS demo

* docs: add feedback components TS demo

* docs: add other components TS demo

* chore(deps): add types

* docs: unified demo code style

* docs: fix lint error

* docs: add demo TS type

* docs: fix demo TS type

* test: update snapshot

* docs: fix TS demo

* feat: update Rate character type

* docs: fix lint error

* feat: update Rate character type

* feat: update Rate character type
2022-05-19 09:46:26 +08:00

2.3 KiB
Raw Blame History

order iframe reactRouter title
3 200 react-router-dom
zh-CN en-US
react-router V6 react-router V6

zh-CN

react-router@6+ 结合使用,生成和路由绑定的面包屑。

en-US

Used together with react-router@6+.

import React from 'react';
import { HashRouter, Route, Routes, Link, useLocation } from 'react-router-dom';
import { Breadcrumb, Alert } from 'antd';

const Apps = () => (
  <ul className="app-list">
    <li>
      <Link to="/apps/1">Application1</Link><Link to="/apps/1/detail">Detail</Link>
    </li>
    <li>
      <Link to="/apps/2">Application2</Link><Link to="/apps/2/detail">Detail</Link>
    </li>
  </ul>
);

const breadcrumbNameMap: Record<string, string> = {
  '/apps': 'Application List',
  '/apps/1': 'Application1',
  '/apps/2': 'Application2',
  '/apps/1/detail': 'Detail',
  '/apps/2/detail': 'Detail',
};

const Home = () => {
  const location = useLocation();
  const pathSnippets = location.pathname.split('/').filter(i => i);

  const extraBreadcrumbItems = pathSnippets.map((_, index) => {
    const url = `/${pathSnippets.slice(0, index + 1).join('/')}`;
    return (
      <Breadcrumb.Item key={url}>
        <Link to={url}>{breadcrumbNameMap[url]}</Link>
      </Breadcrumb.Item>
    );
  });

  const breadcrumbItems = [
    <Breadcrumb.Item key="home">
      <Link to="/">Home</Link>
    </Breadcrumb.Item>,
  ].concat(extraBreadcrumbItems);

  return (
    <div className="demo">
      <div className="demo-nav">
        <Link to="/">Home</Link>
        <Link to="/apps">Application List</Link>
      </div>
      <Routes>
        <Route path="/apps" element={<Apps />} />
        <Route path="*" element={<span>Home Page</span>} />
      </Routes>
      <Alert style={{ margin: '16px 0' }} message="Click the navigation above to switch:" />
      <Breadcrumb>{breadcrumbItems}</Breadcrumb>
    </div>
  );
};

const App: React.FC = () => (
  <HashRouter>
    <Home />
  </HashRouter>
);

export default App;
.demo {
  margin: 16px;
}
.demo-nav {
  height: 30px;
  margin-bottom: 16px;
  line-height: 30px;
  background: #f8f8f8;
}
.demo-nav a {
  padding: 0 8px;
  line-height: 30px;
}
.app-list {
  margin-top: 16px;
}