项目环境:react 16.13 和 ant-design V4
需求背景是:现在后台管理系统左侧菜单是由后端返回的,其中菜单图标Icon也希望是由后端动态返回的。
现在返回的菜单是这样的:
{
path: '/dashboard',
name: "Dashboard",
title: '首页',
icon: 'DesktopOutlined',
},
{
path:'/user',
title:'用户管理',
icon:'AppstoreOutlined'
},
{`在这里插入代码片`
path: '/icon',
title: '图标',
icon: 'BellOutlined'
},
需要注意的是:这个菜单里面后端返回的的Icon图标必须在ant-design这个框架里可以找到,否则会报下面的错
那么现在我们要如何动态加载后端返回的菜单icon呢
解决办法如下代码:
import React from "react";
import { Menu, } from 'antd';
import * as Icon from '@ant-design/icons';
const { SubMenu } = Menu;
const menus = [
{
path: '/dashboard',
name: "Dashboard",
title: '首页',
icon: 'DesktopOutlined',
},
{
path:'/user',
title:'用户管理',
icon:'AppstoreOutlined',
children:[
{
path: '/user/list',
title: '用户列表'
},
]
},
{
path: '/set',
title: '个人设置',
icon: 'BellOutlined'
},
];
// 递归渲染菜单,
renderMenu = data => {
return data.map(item => {
if (item.children && item.children.length > 0) {
return (
<SubMenu
key={item.path}
title={
<span>
{
item.icon ? <span>{
React.createElement(
Icon[item.icon])
}</span> : ''
}
<span>{item.title}</span>
</span>
}
>
{this.renderMenu(item.children)}
</SubMenu>
);
}
return (
<Menu.Item key={item.path}>
<Link to={item.path} onClick={() => this.handClickTag(item)}>
{
item.icon ? <span>{
React.createElement(
Icon[item.icon])
}</span> : ''
}
<span>{item.title}</span>
</Link>
</Menu.Item>
);
});
};
export default function App() {
return (
<div >
<Menu style={{ height: '50px' }} mode="inline">
{this.renderMenu(menus)}
</Menu>
</div>
);
}
如果大家现在觉得上面有点麻烦,那么下面我再给自己一个简单的demo:
import React from "react";
import * as Icon from '@ant-design/icons';
var iconType = 'MessageOutlined';
export default function App() {
return (
<div >
{
React.createElement(
Icon[iconType],
{
style:{ fontSize: '16px', color: '#08c' }
}
)
}
</div>
);
}