ant-design version is 5.1.1 and the routing version is v6
The new version of the navigation menu routing setup is not quite the same as the old one, and at first I didn’t even know how to write the
Realize the effect:
Code:
import React, { useState } from 'react';
import {
DesktopOutlined,
EditFilled,
PieChartOutlined,
} from '@ant-design/icons';
import { Breadcrumb, Layout, Menu, theme } from 'antd';
import { useNavigate, Routes, Route } from 'react-router-dom'
import "./App.css"
import Home from './pages/home';
import Charts from './pages/charts'
const { Header, Content, Footer, Sider } = Layout;
function getItem (label, key, icon, children) {
return {
key,
icon,
children,
label,
};
}
const items = [
getItem(' bookkeeping ', '/home', <PieChartOutlined />),
getItem(' statistics ', '/charts', <DesktopOutlined />),
];
const App = () => {
const [collapsed, setCollapsed] = useState(false);
const navigate = useNavigate()
const {
token: { colorBgContainer },
} = theme.useToken();
const onClick = (e) => {
navigate(e.key, { replace: true })
}
return (
<Layout
style={{
minHeight: '100vh',
}}
>
<Sider collapsible collapsed={collapsed} onCollapse={(value) => setCollapsed(value)}>
<div className='title' >
<EditFilled />
<span style={{marginLeft: 15}}> </span>
</div>
<Menu theme="dark" defaultSelectedKeys={['1']} mode="inline" items={items} onClick={onClick} />
</Sider>
<Layout className="site-layout">
<Header
style={{
padding: 0,
paddingLeft: 30,
background: colorBgContainer,
}}
>123</Header>
<Content
style={{
margin: '0 16px',
}}
>
<Breadcrumb
style={{
margin: '16px 0',
}}
>
{/* <Breadcrumb.Item>User</Breadcrumb.Item>
<Breadcrumb.Item>Bill</Breadcrumb.Item> */}
</Breadcrumb>
<div
style={{
padding: 24,
minHeight: '75vh',
background: colorBgContainer,
}}
>
<Routes>
<Route exact path="/home" element={<Home />} />
<Route exact path="/charts" element={<Charts />} />
</Routes>
</div>
</Content>
<Footer
style={{
textAlign: 'center',
}}
>
Ant Design ©2018 Created by Ant UED
</Footer>
</Layout>
</Layout>
);
};
export default App;
Lecture:
First, add a click event to the menu of the navigation menu.
Modify the item to get the key value after the click by setting a click event (the key value is the page that the route jumps to)
Print it out.
With the key value obtained, you can use the route’s useNavigate to jump to the page.
Import Routing
import { useNavigate, Routes, Route } from 'react-router-dom'
Setting a click event to jump
Finally, set up the page routing exit (here set up the corresponding page routing exit according to your needs)
Points of Attention:
If the following error occurs, it means that useNavigate can only be used within a component, and the corresponding page component can be used with the<Router
>Wrap it up.
Among other things, my navigation menu is written inside App.js, so my App component wrapper is inside index.js
This completes the routing of the page.