// 自定义组件引入方式一
import {
AppstoreOutlined,
MailOutlined,
SettingOutlined,
} from "@ant-design/icons";
const Icons = {
AppstoreOutlined,
MailOutlined,
SettingOutlined,
}
// 自定义组件引入方式二
// import * as Icons from "@ant-design/icons"; // 注意要先引入icons
import React from 'react'
import { Menu } from "antd";
import "./css/LeftMenu.scss";
import { useState, useEffect } from "react";
const DynamicComponent = ( tag ) => {
if(!tag) return null
if (/[a-z]/.test(tag[0])) {
// 组件名开头为小写字母,内置组件div,input等
const Ele = tag
return <Ele>aaa</Ele>;
} else if (/[A-Z]/.test(tag[0])) {
// 组件名开头为大写字母,自定义组件
const Tag = Icons[tag]; // 变量名必须以大写字母开头
return <Tag />; // 使用标签变量来渲染组件
} else {
// 组件名不符合规范
return null
}
}
export default function LeftMenu() {
const [items, setItems] = useState([
{
label: "Navigation One",
key: "sub1",
icon: "MailOutlined",
children: [
{
label: "Item 1",
key: "g1",
children: [
{
label: "Option 1",
key: "1",
icon: "div",
},
{
label: "Option 2",
key: "2",
},
],
type: "group",
},
{
label: "Item 2",
key: "g2",
children: [
{
label: "Option 3",
key: "3",
},
{
label: "Option 4",
key: "4",
},
],
type: "group",
},
],
},
{
label: "Navigation Two",
key: "sub2",
icon: "AppstoreOutlined",
children: [
{
label: "Option 5",
key: "5",
},
{
label: "Option 6",
key: "6",
},
{
label: "Submenu",
key: "sub3",
children: [
{
label: "Option 7",
key: "7",
},
{
label: "Option 8",
key: "8",
},
],
},
],
},
])
function handleItems() {
const deepFunc = function (arr){
let arr1 = []
arr.forEach(item => {
let obj = {
...item,
icon: DynamicComponent(item.icon)
}
if(item.children && item.children.length) {
obj.children = deepFunc(item.children)
}
arr1.push(obj)
})
return arr1
}
setItems(deepFunc(items))
}
useEffect(() => {
handleItems()
}, [])
const onClick = (e) => {
console.log(e);
};
return (
<Menu
className="left-menu"
onClick={onClick}
defaultSelectedKeys={["1"]}
defaultOpenKeys={["sub1"]}
mode="inline"
items={items}
/>
);
}
react动态添加内置组件及自定义组件
最新推荐文章于 2024-08-13 08:41:29 发布