Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🧐[问题 | question]ProLayout中通过传入menuProps的items属性来控制菜单后匹配路由 #10878

Closed
ZhangXY-Magic opened this issue Aug 7, 2023 · 1 comment
Labels

Comments

@ZhangXY-Magic
Copy link

🧐 问题描述 | Problem description

请问在ProLayout中的RunTimeLayoutConfig里通过传入menuProps的items属性来控制菜单的渲染后,如何同时绑定router处理路由跳转。
目前我想到的就是在menuProps里再传入onClick方法遍历route匹配menu的key 然后用history.push来操作,请问有更规范或者更符合设计的方式么

💻 示例代码 | Sample code

🚑 其他信息 | Other information

OS:

Node:

浏览器 | browser:

@chenshuai2144
Copy link
Collaborator

在ProLayout中,可以通过传入menuProps的items属性来控制菜单的渲染。如果想要同时绑定路由处理,可以使用React Router库中的useHistory hook来进行路由跳转。具体操作如下:

  1. 在ProLayout的menuItemRender属性中,添加一个onClick回调函数,用来处理菜单点击事件。
  2. 在回调函数中,使用React Router的useHistory hook获取history对象。
  3. 使用history.push方法进行路由跳转,传入目标路径。

示例代码如下:

import { ProLayout } from '@ant-design/pro-layout';
import { Link, Outlet, useAppData, useLocation, useHistory } from 'umi';

export default function Layout() {
  const { clientRoutes } = useAppData();
  const location = useLocation();
  const history = useHistory();

  const handleMenuClick = (path: string) => {
    history.push(path);
  };

  return (
    <ProLayout
      route={clientRoutes[0]}
      location={location}
      title="Umi x Ant Design"
      menuItemRender={(menuItemProps, defaultDom) => {
        if (menuItemProps.isUrl || menuItemProps.children) {
          return defaultDom;
        }
        if (menuItemProps.path && location.pathname !== menuItemProps.path) {
          return (
            <a onClick={() => handleMenuClick(menuItemProps.path)}>
              {defaultDom}
            </a>
          );
        }
        return defaultDom;
      }}
    >
      <Outlet />
    </ProLayout>
  );
}

在上述代码中,我们在menuItemRender方法中通过a标签模拟菜单项的点击事件,并通过handleMenuClick方法进行路由跳转。这样,当菜单项被点击时,会触发handleMenuClick方法,通过history.push进行路由跳转。

这种方式能够实现菜单项和路由的绑定,同时符合React的设计理念和规范。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants