React中使用antd组件写导航栏页面刷新菜单高亮状态被重置
解决代码:
// 导航栏
import React, { useState } from 'react';
import { NavLink, useLocation } from 'react-router-dom'
import { Menu } from 'antd';
const items: MenuProps['items'] = [
{
label: (
<NavLink to="/home">
主页
</NavLink>
),
key: 'home', //key值要与路由文件中的path值相同
},
{
label: (
<NavLink to="/about">
关于
</NavLink>
),
key: 'about',
},
];
function Nav() {
const { pathname } = useLocation(); //用useLocation中的pathname获取当前页面的url,得到的是 /xxx
const newpathname = pathname.replace('/', '') //去掉 /
const [current, setCurrent] = useState(newpathname); //current控制菜单栏高亮位置,将得到和路由一样的的的路径给current就可以刷新之前高亮那个页面,刷新之后还高亮那个页面
// console.log('a', current)
const onClick: MenuProps['onClick'] = e => {
console.log('click ', e);
setCurrent(e.key);
};
return(
<div>
<Menu onClick={onClick} selectedKeys={[current]} mode="horizontal" items={items} />
</div>
)
}
export default Nav;