You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何从对象动态渲染Material UI图标组件?

动态渲染Material UI图标的解决方案

问题核心在于你把组件名以字符串形式存储,直接用<icon/>时,React会将小写的icon识别为原生HTML标签,而非你导入的Material UI组件。以下是扩展性更好的解决方法:

步骤1:创建图标映射表

先将导入的图标组件与对应的字符串名称建立映射关系:

import {
  DirectionsCarFilledOutlined,
  PhoneIphoneOutlined,
} from "@mui/icons-material";

// 建立图标名称到组件的映射
const IconMap = {
  DirectionsCarFilledOutlined,
  PhoneIphoneOutlined
};

const list = [
  {title: 'Vehicle', icon: 'DirectionsCarFilledOutlined'},
  {title: 'Electronic', icon: 'PhoneIphoneOutlined'},
];

步骤2:动态渲染图标

在map遍历中,从映射表取出对应组件并渲染:

{list.map(({ title, icon: iconName }) => {
  // 获取对应的图标组件
  const Icon = IconMap[iconName];
  // 处理不存在的图标,避免渲染错误
  if (!Icon) return null;
  
  return (
    <div key={title}>
      <p>{title}</p>
      <div><Icon /></div>
    </div>
  );
})}

优势说明

后续新增图标时,只需两步即可适配:

  1. 导入新的Material UI图标组件
  2. 在IconMap中添加新的键值对
    完全不需要修改switch case或遍历逻辑,扩展性拉满。

内容的提问来源于stack exchange,提问作者Solid1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 20:54:17