如何使和侧边栏菜单项活动取决于当前的url?



我使用和菜单和菜单项组件。我的应用程序是这样的,如果你点击一个特定的菜单项的url改变,该菜单项被选中。然而,如果你在仪表板上,你也可以点击一个按钮,将url更改为与点击该特定菜单项相同的url,但在这种情况下,菜单项不会被选中。如何解决这个问题:

<Menu
onClick={this.handleClick}
mode="vertical"
>
<Link to="/dashboard">
<Menu.Item key="mail" icon={<MailOutlined />}>
Dashboard
</Menu.Item>
</Link>
<Link to="/add-recipe">
<Menu.Item key="app" disabled icon={<AppstoreOutlined />}>
Add Recipes
</Menu.Item>
</Link>
</Menu>

现在在仪表板组件中还有一个按钮,允许用户直接从那里添加配方并在单击时更改url,但是没有选择添加配方菜单项,因为没有手动单击它。如何使它活跃取决于url?

我遇到了同样的问题,我不得不在Menu中使用道具selectedKeys,并使用hook和state来设置所选的当前项目。要使其工作,键必须具有与链接相同的值。

例子:

function Navigation() {
let location = useLocation();
const [current, setCurrent] = useState(
location.pathname === "/" || location.pathname === ""
? "/dashboard"
: location.pathname,
);
//or simply use const [current, setCurrent] = useState(location.pathname)        
useEffect(() => {
if (location) {
if( current !== location.pathname ) {
setCurrent(location.pathname);
}
}
}, [location, current]);
function handleClick(e: any) {
setCurrent(e.key);
}
return (
<Menu
onClick={handleClick}
mode="vertical"
selectedKeys={[current]}
>
<Link to="/dashboard">
<Menu.Item key="/dashboard" icon={<MailOutlined />}>
Dashboard
</Menu.Item>
</Link>
<Link to="/add-recipe">
<Menu.Item key="/add-recipe" disabled icon={<AppstoreOutlined />}>
Add Recipes
</Menu.Item>
</Link>
</Menu>
);
}
export default Navigation;
const useStyles = makeStyles((theme: Theme) =>
createStyles({
root: {
display: 'flex',
'& .MuiPaper-root': {
backgroundColor: '#ffffff',
},
},
active: {
color: theme.palette.primary.main,
'& .MuiTypography-body1': {
fontWeight: 600,
},
// backgroundColor: 'green'
'& .MuiListItemIcon-root': {
color: theme.palette.primary.main,
},
},
}),
);

const [activeLink, setActiveLink] = useState('');

useEffect(() => {
setActiveLink(window.location.pathname);
}, []);

现在在您的菜单。

<Menu.Item
className={{path-from-fetched-from-onClick)} === activeLink ? `${classes.active}` : ''}>
...
</Menu.Item>

这可能是你必须在你的链接上应用这个,而不是菜单项。但我相信它会解决问题的。

最新更新