1.在src/utils目录下新建一个fixMenuItemIcon.js文件,创建一个function fixMenuItemIcon来正常显示菜单图标
2.复制以下代码到fixMenuItemIcon.js文件中
import React from 'react';import * as allIcons from '@ant-design/icons';function fixMenuItemIcon(menus, iconType = 'Outlined') {if (menus && menus.length > 0) {menus.forEach((item) => {const { icon, children } = item;if (icon && typeof icon === 'string') {const fixIconName = icon.slice(0, 1).toLocaleUpperCase() + icon.slice(1) + iconType;let iconObject ='';if(typeof allIcons[fixIconName] !== 'undefined'){iconObject = React.createElement(allIcons[fixIconName]);}else if(typeof allIcons[icon] !== 'undefined'){iconObject = React.createElement(allIcons[icon]);}item.icon = iconObject;}children && children.length > 0 ? (item.children = fixMenuItemIcon(children)) : null;});}return menus;}export default fixMenuItemIcon;
3.这段代码稍作说明,遍历所有菜单item,根据菜单的icon属性,创建对应的Outlined类型图标对象,改完后item.icon是一个真正的antd pro图标对象,如果图标名称是antd pro中不存在的图标,那么item.icon=’’;
if (icon && typeof icon === 'string') {const fixIconName = icon.slice(0, 1).toLocaleUpperCase() + icon.slice(1) + iconType;let iconObject ='';if(typeof allIcons[fixIconName] !== 'undefined'){iconObject = React.createElement(allIcons[fixIconName]);}else if(typeof allIcons[icon] !== 'undefined'){iconObject = React.createElement(allIcons[icon]);}item.icon = iconObject;}
4.如果菜单有子菜单,递归做同样的操作,即给菜单配上真正的图标
children && children.length > 0 ? (item.children = fixMenuItemIcon(children)) : null;
});
5.fixMenuItemIcon.js写完后,我们要在src/app.jsx中调用一下,在app.jsx中引入fixMenuItemIcon
import fixMenuItemIcon from '@/utils/fixMenuItemIcon';
6.在 menuDataRender: () =>{ return initialState?.menuData },这行代码中加入fixMenuItemIcon方法
menuDataRender: () =>{return fixMenuItemIcon(initialState?.menuData);},
7.保存,等编译通过后,重新登录查看下菜单数据,顺利的话,菜单图标会正常显示,如下图
