在React中使用动态图标

2023-12-13 04:43:44

背景

需要按名称引入图标

安装

yarn add react-icons

实现

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>)

示例

<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>

文章来源:https://blog.csdn.net/jgku/article/details/134954294
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。