63 lines
1.6 KiB
TypeScript
63 lines
1.6 KiB
TypeScript
import { useMemo } from 'react';
|
|
import { useLocation, useNavigate } from 'react-router-dom';
|
|
import { Menu } from 'antd';
|
|
import type { MenuProps } from 'antd';
|
|
import { routeMenuConfig } from './menuConfig';
|
|
import './SidebarMenu.css';
|
|
|
|
interface SidebarMenuProps {
|
|
collapsed: boolean;
|
|
onMenuClick?: () => void;
|
|
}
|
|
|
|
const SidebarMenu = ({ collapsed, onMenuClick }: SidebarMenuProps) => {
|
|
const location = useLocation();
|
|
const navigate = useNavigate();
|
|
|
|
const menuItems: MenuProps['items'] = useMemo(() => {
|
|
const children = routeMenuConfig.map((config) => ({
|
|
key: config.key,
|
|
icon: config.icon,
|
|
label: config.label,
|
|
}));
|
|
return [
|
|
{
|
|
type: 'group' as const,
|
|
label: collapsed ? '' : '主要功能',
|
|
className: 'menu-section-title',
|
|
children,
|
|
},
|
|
];
|
|
}, [collapsed]);
|
|
|
|
const selectedKeys = useMemo(() => {
|
|
const path = location.pathname;
|
|
if (path === '/' || path === '') {
|
|
return [routeMenuConfig[0].key];
|
|
}
|
|
const config = routeMenuConfig.find((item) => path.startsWith(item.path));
|
|
return [config ? config.key : path];
|
|
}, [location.pathname]);
|
|
|
|
const handleMenuClick: MenuProps['onClick'] = ({ key }) => {
|
|
navigate(key);
|
|
if (onMenuClick) onMenuClick();
|
|
};
|
|
|
|
return (
|
|
<div className="sidebar-menu-container">
|
|
<Menu
|
|
theme="dark"
|
|
mode="inline"
|
|
inlineCollapsed={collapsed}
|
|
selectedKeys={selectedKeys}
|
|
items={menuItems}
|
|
onClick={handleMenuClick}
|
|
className="sidebar-menu"
|
|
/>
|
|
</div>
|
|
);
|
|
};
|
|
|
|
export default SidebarMenu;
|