在Ant Design的<Menu>组件中,要根据当前路径动态设置激活(active)的菜单项,直接在Menu组件中根据window.location.pathname匹配不起作用

主要原因: 在渲染之后再判断找不到对应的key而已

首先,我们需要找到与当前路径匹配的菜单项,并将其ID作为defaultActiveKey传递给

组件。假设你的menu数组结构如下:

1const menu = [
2  { id: '1', linkTo: '/path1', title: '菜单1' },
3  { id: '2', linkTo: '/path2', title: '菜单2' },
4  // 更多...
5];

然后,在组件渲染之前计算出匹配当前路径的菜单项ID:

1import { useLocation } from 'react-router-dom';
2import _ from 'lodash';
3
4function YourComponent() {
5  const location = useLocation();
6  const currentPath = location.pathname;
7
8  // 找到与当前路径匹配的菜单项ID
   // 这里最重要了,要在下面menu组件渲染之前做出计算
9  const activeItemId = menu?.find(itm => _.includes(currentPath, itm.linkTo))?.id;
10
11  return (
12     ({
16        key: itm?.id,
17        label: (
18          
19            {itm?.title}
20          
21        ),
22      }))}
23    />
24  );
25}

这样,当页面加载时,与当前URL路径匹配的菜单项将会被自动激活。

你可能感兴趣的:(前端,php,前端,javascript)