13.自动选中当前菜单项和子菜单项刷新页面自动打开状态保持
React-router-dom v6版本需要做如下操作:
1.菜单被选中,在components/left-nav/left-nav.jsx 文件下代码如下:
/* 左侧导航的组件 */ import React from "react"; import { Link, useNavigate, useLocation} from 'react-router-dom' import {Menu} from "antd"; import logo from '../../assets/logo.png' import './index.css' import menuList from "../../config/menuConfig" export default function LeftNav (){ const navigate = useNavigate() // 获取当前页面路径上path const current_path_obj = useLocation() // 返回一个对象 {pathname: '/role', search: '', hash: '', state: null, key: 'fmqz5mcg'} console.log("current path ==", current_path_obj.pathname) // 这里把 defaultSelectedKeys 改为 selectedKeys 是因为有个重定向问题 return ( <div className="left-nav"> <Link to="/" className="left-nav-header"> <img src={logo} alt="logo"/> <h1>XXXXX</h1> </Link> <Menu theme="dark" mode="inline" selectedKeys = {[current_path_obj.pathname]} onClick={({key}) => { console.log("to " , key) navigate(key) }} items={menuList} /> </div> ) }
2.子菜单项打开状态保持实现如下:
/* 左侧导航的组件 */ import React from "react"; import { Link, useNavigate, useLocation} from 'react-router-dom' import {Menu} from "antd"; import logo from '../../assets/logo.png' import './index.css' import menuList from "../../config/menuConfig" // 定一个函数来判断当前选中的路由是否需要打开,前提是有子路由 const getOpenKey = (url_key_str,keys) => { let openKey = '' keys.forEach(item => { if(item.children){ item.children.forEach(subItem => { if (url_key_str === subItem.key){ openKey = item.key } // 因为有嵌套列表所以需要递归 if(subItem.children){ getOpenKey(item.children) } }) } }) return openKey } export default function LeftNav (){ const navigate = useNavigate() // 获取当前页面路径上path const current_path_obj = useLocation() // 返回一个对象 {pathname: '/role', search: '', hash: '', state: null, key: 'fmqz5mcg'} console.log("current path ==", current_path_obj.pathname) // 这里把 defaultSelectedKeys 改为 selectedKeys 是因为有个重定向问题 return ( <div className="left-nav"> <Link to="/" className="left-nav-header"> <img src={logo} alt="logo"/> <h1>XXXXX</h1> </Link> <Menu theme="dark" mode="inline" selectedKeys = {[current_path_obj.pathname]} defaultOpenKeys = {[getOpenKey(current_path_obj.pathname, menuList)]} onClick={({key}) => { console.log("to " , key) navigate(key) }} items={menuList} /> </div> ) }