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

React中如何通过map循环渲染Material UI图标列表?

解决Material UI图标循环渲染失效问题

你的代码里有几个关键问题导致渲染失败:

  1. 数组存储错误:你直接把<Computer />这类已实例化的图标元素放进数组,后续没法给它们动态添加sx这类props;而且React组件变量名必须大写,你用<icon />会被当成普通HTML标签,自然不生效。
  2. Key设置无效:已实例化的图标元素没有id属性,key={icon.id}等于没设key,React会报警告。
  3. JSX结构不完整:你的div和外层Fragment都没闭合,语法错误也会导致渲染失败。
  4. 样式传递错误:直接写width={100}这类属性无效,Material UI的元素样式需要通过sx对象传递。

修正后的代码

import React from "react";
import { IconButton } from "@mui/material";
import {
  Computer,
  Inventory,
  Medication,
  Gavel,
  MilitaryTech,
  ContentCut,
  SportsMma,
  LocalDining,
  Synagogue,
  Diversity1,
  Security,
  Event,
} from "@mui/icons-material";

export function MadorimIcons() {
  // 存储组件本身,而非实例化元素
  const icons = [
    Computer,
    Inventory,
    Medication,
    Gavel,
    MilitaryTech,
    ContentCut,
    SportsMma,
    LocalDining,
    Synagogue,
    Diversity1,
    Security,
    Event,
  ];

  return (
    <>
      <div
        sx={{
          width: 100,
          display: "flex",
          position: "absolute",
          alignItems: "center",
          whiteSpace: "normal",
          gap: 5,
        }}
      >
        {icons.map((IconComponent, index) => (
          <IconButton color="primary" key={index}>
            {/* 大写组件名,动态传递sx props */}
            <IconComponent sx={{ fontSize: "15vw" }} />
          </IconButton>
        ))}
      </div>
    </>
  );
}

关键修正点说明

  • 数组存储组件本身(比如Computer而非<Computer />),这样就能灵活传递sx等props。
  • React组件名必须大写,用IconComponent作为变量名,避免被识别为HTML标签。
  • 用数组索引index作为key(如果后续图标不会排序/增删,这是安全的;如果有动态操作,建议给每个图标加唯一标识)。
  • 把所有样式属性统一放进sx对象,符合Material UI的样式传递规则。
  • 补全未闭合的JSX标签,修复语法错误。

如果非要存储实例化元素(不推荐,灵活性差),可以这样改,但无法添加新props:

{icons.map((icon, index) => (
  <IconButton color="primary" key={index}>
    {icon}
  </IconButton>
))}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 09:05:30