背景
需要按名称引入图标
安装
yarn add react-icons
实现
typescript
import loadable from "@loadable/component"
import { IconBaseProps, IconType } from "react-icons/lib"
interface typesPropsIcon {
nameIcon: string;
propsIcon?: IconBaseProps
}
export function Icon({ nameIcon, propsIcon }: typesPropsIcon): JSX.Element {
const lib = nameIcon.replace(/([a-z0-9])([A-Z])/g, '$1 $2').split(" ")[0].toLocaleLowerCase();
const ElementIcon: IconType = loadable(() => import(`react-icons/${lib}/index.js`), {
resolveComponent: (el: JSX.Element) => el[nameIcon as keyof JSX.Element]
});
return (<span style={{paddingRight: 6}}><ElementIcon {...propsIcon} style={{size: '1em'}}/></span>)
示例
typescript
<Space direction="horizontal">
<Menu
mode="inline"
style={{ width: 500, height:'fit-content' }}
items={[
{ key: 'mail', label: 'Mail1', icon: <MailOutlined />, type:'group' },
{ key: 'mail2', label: 'Mail2', icon: <Icon nameIcon="AiFillBug" propsIcon={{ size: 20 }} /> },
{ key: 'mail3', label: 'Mail3', icon: <Icon nameIcon="AiFillInsurance" propsIcon={{ size: 20 }}/> },
{ key: 'mail4', label: 'Mail4', icon: <Icon nameIcon="AiFillDollarCircle" propsIcon={{ size: 20 }}/> },
{ key: 'mail5', label: 'Mail5', icon: <Icon nameIcon="AiOutlineApartment" propsIcon={{ size: 20 }}/> },
]}
/>
<Menu
mode="inline"
style={{ width: 256, height:'fit-content', marginLeft: 4}}
items={[
{ key: 'mail11', label: ' Mail1', icon: <Icon nameIcon="BiAperture" propsIcon={{ size: 20 }}/>, type:'group' },
{ key: 'mail21', label: ' Mail2', icon: <Icon nameIcon="CiBasketball" propsIcon={{ size: 20 }}/> },
{ key: 'mail31', label: ' Mail3', icon: <Icon nameIcon="CiBadgeDollar" propsIcon={{ size: 20 }}/> },
{ key: 'mail41', label: ' Mail4', icon: <Icon nameIcon="CiBoxList" propsIcon={{ size: 20, marginRight: 80, marginBottom: 10 }}/> },
{ key: 'mail51', label: ' Mail5', icon: <ClusterOutlined /> },
]}
/>
</Space>