如何根据当前 url 激活 antd 侧边栏菜单项?

How to make antd sidebar menu items active depending on the current url?

我正在使用 antd 菜单和菜单项组件。我的应用程序是这样的,如果您单击特定的菜单项,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?

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 中应用有效的 class。

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

您可能必须将此应用于 Link,而不是菜单项。但我相信它会解决问题。

我遇到了同样的问题,我不得不使用Menu中的道具selectedKeys,并使用钩子和状态来设置当前选中的项目。 要使其有效,键必须具有与 link.

相同的值

示例:

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;