用React + MUI + react-router-dom创建Navigator

环境

    • React

 

    • MUI

 

    react-router-dom

绘制/划定画图

我希望在左侧的导航器上,突出显示当前所在的页面。

image.png

请参考以下的样本。

 

代码

因为原先没有跳转到链接页面并突出显示转移后的机制,所以需要进行添加。

为了将ListItemButton的Active设置为true,
请比较使用useLocation()获取的location的pathname与链接(to)的相似性。

export default function Navigator(props) {
  const { ...other } = props

  const location = useLocation()

  return (

我认为在React + MUI中,可以使用ListItem或ListItemButton来创建菜单。
要将NavLink与ListItem组合在一起,可以使用component={NavLink}来指定。

<ListItem  key={childId} disablePadding component={NavLink}
to={to}>
    <ListItemButton
        selected={location.pathname===to}
        sx={item}
    >
        <ListItemIcon>{icon}</ListItemIcon>
        <ListItemText>{childId}</ListItemText>
    </ListItemButton>
</ListItem>

点击后,我考虑将原始数据的active属性设置为false…但仔细想了想,发现只需将其与当前URL进行比较,所以我留下了备忘录。

bannerAds