1. 嵌套路由
1.1 写法一
App.tsx
import React from 'react';
import { Router } from '@reach/router';
import { Login } from './pages/Login/Login';
import { Home } from './pages/Home/Home';
import './App.css';
export default function App() {
return (
<Router>
<Login path="/login" />
<Home path="/*" />
</Router>
);
}
Home.tsx
import React, { useState } from 'react';
import { Layout, Menu, Icon, Breadcrumb } from 'antd';
import { Router, RouteComponentProps } from '@reach/router';
import './style.css';
import { AddArticle } from '../AddArticle/AddArticle';
const { Header, Sider, Content, Footer } = Layout;
const { SubMenu } = Menu;
export const Home: React.FC<RouteComponentProps> = (props) => {
...
return (
<Layout style={{ minHeight: '100vh' }}>
...
<Content
style={{
margin: '24px 16px',
padding: 24,
background: '#fff',
minHeight: 280,
}}
>
<Router> // 设置路由
<AddArticle path="/add" />
</Router>
</Content>
<Footer style={{ textAlign: 'center' }}>
Blog Platform © Chenxii
</Footer>
</Layout>
</Layout>
);
};
AddArticle.tsx 【注意一定要传泛型进入组件,若父级传过来一些额外的参数,那就在这个组件写个接口extends RouteComponentProps】
import React from 'react';
import { RouteComponentProps } from '@reach/router';
export const AddArticle: React.FC<RouteComponentProps> = () => {
return <div>添加文章</div>;
};
1.2 写法二
App.tsx
import React from 'react';
import { Router } from '@reach/router';
import { Login } from './pages/Login/Login';
import { Home } from './pages/Home/Home';
import { AddArticle } from './pages/AddArticle/AddArticle';
import './App.css';
export default function App() {
return (
<Router>
<Login path="/login" />
<Home path="/">
<AddArticle path="add" />
</Home>
</Router>
);
}
Home.tsx
import React, { useState } from 'react';
import { Layout, Menu, Icon, Breadcrumb } from 'antd';
import { RouteComponentProps } from '@reach/router';
import './style.css';
const { Header, Sider, Content, Footer } = Layout;
const { SubMenu } = Menu;
export const Home: React.FC<RouteComponentProps> = (props) => {
...
return (
<Layout style={{ minHeight: '100vh' }}>
...
<Content
style={{
margin: '24px 16px',
padding: 24,
background: '#fff',
minHeight: 280,
}}
>
{props.children} // 这里!
</Content>
<Footer style={{ textAlign: 'center' }}>
Blog Platform © Chenxii
</Footer>
</Layout>
</Layout>
);
};
AddArticle.tsx 同写法一