The ant-design version is 5.1.1, and the routing version is v6. The
navigation menu routing settings of the new version are different from those of the old version. I didn’t even know how to write them at the beginning.
Realization 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('记账', '/home', <PieChartOutlined />),
getItem('统计', '/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;
explain:
First, add a click event to the menu of the navigation menu
Modify the item and obtain the key value after the click by setting the click event (the key value is the page that the route jumps to)
Print it out and take a look
The obtained key value can be used to jump to the page using the route's useNavigate.
Import route
import {
useNavigate, Routes, Route } from 'react-router-dom'
Set click event jump
Finally, set the page routing exit (here set the corresponding page routing exit according to your own needs)
important point:
If the following error occurs, useNavigate must be used within the component. Wrap the corresponding page component with <Router
>
. My navigation menu is written in App.js, so my App component is wrapped in index. In .js,
this completes the routing settings for the page.