ant design pro v5 自定义侧边栏收缩按钮位置

ant design pro v5 自定义侧边栏收缩按钮位置

图:
在这里插入图片描述

1.升级ant design pro v5以后layout隐藏,相关配置放到了app.tsx
layout 的配置代码如下:

export const layout: RunTimeLayoutConfig = ({ initialState }) => {
  return {
    rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    waterMarkProps: {
      content: initialState?.currentUser?.name,
    },
    footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      // 如果没有登录,重定向到 login
      if (!initialState?.currentUser && location.pathname !== loginPath) {
        history.push(loginPath);
      }
    },
    links: isDev
      ? [
          <Link to="/umi/plugin/openapi" target="_blank">
            <LinkOutlined />
            <span>OpenAPI 文档</span>
          </Link>,
          <Link to="/~docs">
            <BookOutlined />
            <span>业务组件文档</span>
          </Link>,
        ]
      : [],
    menuHeaderRender: undefined,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    ...initialState?.settings,
  };
};

通过官方文档
在这里插入图片描述
我们主要关注红框里面的参数。

那么我们开始动手:

  1. 首先在 components 下新增 HeaderContent.
    在这里插入图片描述
import React from 'react';
import useMergedState from 'rc-util/es/hooks/useMergedState';
import { MenuFoldOutlined, MenuUnfoldOutlined } from '@ant-design/icons';

export type HeaderContent = {
  collapse?: boolean;
  onCollapse?: (collapsed: boolean) => void;
};

// eslint-disable-next-line @typescript-eslint/no-redeclare
const HeaderContent: React.FC<HeaderContent> = (props) => {
  const [collapsed, setCollapsed] = useMergedState<boolean>(props.collapse ?? false, {
    value: props.collapse,
    onChange: props.onCollapse,
  });

  return (
    <>
      <div
        onClick={() => setCollapsed(!collapsed)}
        style={{
          cursor: 'pointer',
          fontSize: '16px',
        }}
      >
        {collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
      </div>
    </>
  );
};

export default HeaderContent;

  1. 修改 app.tsx 下getInitialState() 方法。
    新增collapsed?: boolean;
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: API.CurrentUser;
  collapsed?: boolean;
  fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
}> {
  const fetchUserInfo = async () => {
    try {
      const msg = await queryCurrentUser();
      return msg.data;
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };
  // 如果是登录页面,不执行
  if (history.location.pathname !== loginPath) {
    const currentUser = await fetchUserInfo();
    return {
      fetchUserInfo,
      currentUser,
      settings: {},
    };
  }
  return {
    fetchUserInfo,
    settings: {},
  };
}

3.修改 RunTimeLayoutConfig 改动地方我都加了注释。

export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
  const onCollapse = (collapsed: boolean): void => {
    setInitialState({ ...initialState, collapsed }).then();
  };
  return {
    rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    waterMarkProps: {
      content: initialState?.currentUser?.name,
    },
    // 自定义头内容的方法  我把 自定义侧边栏收缩按钮位置 方在这里
    headerContentRender: () => (
      <HeaderContent collapse={initialState?.collapsed} onCollapse={onCollapse} />
    ),
    // 去掉系统自带
    collapsedButtonRender: false,
    // 指定配置collapsed
    collapsed: initialState?.collapsed,
    // 菜单的折叠收起事件
    onCollapse: onCollapse,
    footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      if (!initialState?.currentUser && location.pathname !== loginPath) {
        history.push(loginPath);
      }
    },
    links: isDev
      ? [
          <Link to="/umi/plugin/openapi" target="_blank">
            <LinkOutlined />
            <span>OpenAPI 文档</span>
          </Link>,
          <Link to="/~docs">
            <BookOutlined />
            <span>业务组件文档</span>
          </Link>,
        ]
      : [],
    menuHeaderRender: undefined,
    ...initialState?.settings,
  };
  

4.修改后整个app.tsx 代码如下:

import type { Settings as LayoutSettings } from '@ant-design/pro-layout';
import { PageLoading } from '@ant-design/pro-layout';
import type { RunTimeLayoutConfig } from 'umi';
import { history, Link } from 'umi';
import RightContent from '@/components/RightContent';
import Footer from '@/components/Footer';
import { currentUser as queryCurrentUser } from './services/ant-design-pro/api';
import { BookOutlined, LinkOutlined } from '@ant-design/icons';
import HeaderContent from "@/components/HeaderContent";

const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/user/login';

/** 获取用户信息比较慢的时候会展示一个 loading */
export const initialStateConfig = {
  loading: <PageLoading />,
};

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: API.CurrentUser;
  collapsed?: boolean;
  fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
}> {
  const fetchUserInfo = async () => {
    try {
      const msg = await queryCurrentUser();
      return msg.data;
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };
  // 如果是登录页面,不执行
  if (history.location.pathname !== loginPath) {
    const currentUser = await fetchUserInfo();
    return {
      fetchUserInfo,
      currentUser,
      settings: {},
    };
  }
  return {
    fetchUserInfo,
    settings: {},
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
  const onCollapse = (collapsed: boolean): void => {
    setInitialState({ ...initialState, collapsed }).then();
  };
  return {
    rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    waterMarkProps: {
      content: initialState?.currentUser?.name,
    },
    headerContentRender: () => (
      <HeaderContent collapse={initialState?.collapsed} onCollapse={onCollapse} />
    ),
    collapsedButtonRender: false,
    collapsed: initialState?.collapsed,
    onCollapse: onCollapse,
    footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      // 如果没有登录,重定向到 login
      if (!initialState?.currentUser && location.pathname !== loginPath) {
        history.push(loginPath);
      }
    },
    links: isDev
      ? [
          <Link to="/umi/plugin/openapi" target="_blank">
            <LinkOutlined />
            <span>OpenAPI 文档</span>
          </Link>,
          <Link to="/~docs">
            <BookOutlined />
            <span>业务组件文档</span>
          </Link>,
        ]
      : [],
    menuHeaderRender: undefined,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    ...initialState?.settings,
  };
};

最后git贴出来:
git地址

  • 11
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Ant Design Pro 是一个企业级 UI 设计语言和 React 组件库,提供了丰富的组件和模板,可以帮助开发者快速构建现代化的 Web 应用。在 Ant Design Pro 中,菜单是一个非常重要的组件,可以用来实现应用的导航和路由功能。同时,Ant Design Pro 也提供了自定义菜单 icon 的功能,可以让开发者更好地定制自己的应用。 在 Ant Design Pro 中,菜单的 icon 可以通过修改菜单项的 icon 属性来实现。例如,如果我们想要给一个菜单项添加一个自定义的 icon,可以按照如下方式进行: ```javascript { path: '/dashboard', name: 'Dashboard', icon: 'dashboard', // 默认使用 Ant Design 的 icon // ... }, { path: '/custom', name: 'Custom', icon: <Icon type="smile" />, // 使用自定义 icon // ... } ``` 在上面的代码中,我们可以看到,我们可以使用 Ant Design 提供的 icon 字符串,也可以使用自定义的 icon 组件,只需要将其作为 icon 属性的值即可。 需要注意的是,在使用自定义 icon 组件时,我们需要先引入对应的 icon 组件,例如: ```javascript import { Icon } from '@ant-design/icons'; import { SmileOutlined } from '@ant-design/icons'; const IconSmile = props => <Icon component={SmileOutlined} {...props} />; ``` 然后再将其作为菜单项的 icon 属性的值即可: ```javascript { path: '/custom', name: 'Custom', icon: <IconSmile />, // ... } ``` 这样就可以实现自定义菜单 icon 的功能了。同时,Ant Design Pro 还提供了丰富的 icon 组件,开发者可以根据自己的需求选择使用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值