1. 嵌套路由

1.1 写法一

App.tsx

  1. import React from 'react';
  2. import { Router } from '@reach/router';
  3. import { Login } from './pages/Login/Login';
  4. import { Home } from './pages/Home/Home';
  5. import './App.css';
  6. export default function App() {
  7. return (
  8. <Router>
  9. <Login path="/login" />
  10. <Home path="/*" />
  11. </Router>
  12. );
  13. }

Home.tsx

  1. import React, { useState } from 'react';
  2. import { Layout, Menu, Icon, Breadcrumb } from 'antd';
  3. import { Router, RouteComponentProps } from '@reach/router';
  4. import './style.css';
  5. import { AddArticle } from '../AddArticle/AddArticle';
  6. const { Header, Sider, Content, Footer } = Layout;
  7. const { SubMenu } = Menu;
  8. export const Home: React.FC<RouteComponentProps> = (props) => {
  9. ...
  10. return (
  11. <Layout style={{ minHeight: '100vh' }}>
  12. ...
  13. <Content
  14. style={{
  15. margin: '24px 16px',
  16. padding: 24,
  17. background: '#fff',
  18. minHeight: 280,
  19. }}
  20. >
  21. <Router> // 设置路由
  22. <AddArticle path="/add" />
  23. </Router>
  24. </Content>
  25. <Footer style={{ textAlign: 'center' }}>
  26. Blog Platform &copy; Chenxii
  27. </Footer>
  28. </Layout>
  29. </Layout>
  30. );
  31. };

AddArticle.tsx 【注意一定要传泛型进入组件,若父级传过来一些额外的参数,那就在这个组件写个接口extends RouteComponentProps】

  1. import React from 'react';
  2. import { RouteComponentProps } from '@reach/router';
  3. export const AddArticle: React.FC<RouteComponentProps> = () => {
  4. return <div>添加文章</div>;
  5. };

1.2 写法二

App.tsx

  1. import React from 'react';
  2. import { Router } from '@reach/router';
  3. import { Login } from './pages/Login/Login';
  4. import { Home } from './pages/Home/Home';
  5. import { AddArticle } from './pages/AddArticle/AddArticle';
  6. import './App.css';
  7. export default function App() {
  8. return (
  9. <Router>
  10. <Login path="/login" />
  11. <Home path="/">
  12. <AddArticle path="add" />
  13. </Home>
  14. </Router>
  15. );
  16. }

Home.tsx

  1. import React, { useState } from 'react';
  2. import { Layout, Menu, Icon, Breadcrumb } from 'antd';
  3. import { RouteComponentProps } from '@reach/router';
  4. import './style.css';
  5. const { Header, Sider, Content, Footer } = Layout;
  6. const { SubMenu } = Menu;
  7. export const Home: React.FC<RouteComponentProps> = (props) => {
  8. ...
  9. return (
  10. <Layout style={{ minHeight: '100vh' }}>
  11. ...
  12. <Content
  13. style={{
  14. margin: '24px 16px',
  15. padding: 24,
  16. background: '#fff',
  17. minHeight: 280,
  18. }}
  19. >
  20. {props.children} // 这里!
  21. </Content>
  22. <Footer style={{ textAlign: 'center' }}>
  23. Blog Platform &copy; Chenxii
  24. </Footer>
  25. </Layout>
  26. </Layout>
  27. );
  28. };

AddArticle.tsx 同写法一