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

React组件渲染报错:元素类型无效,求Icon传参解决方案

问题解决:Element type is invalid 报错及Icon传参实现

错误原因

你在constants/drawer里存储的是已经渲染完成的JSX元素(<DashboardIcon />),而非组件本身。当你在main.js里把它解构为Icon并尝试以<Icon size="small"/>的方式调用时,React会把它当成组件类型,但实际上它是一个已生成的元素实例,无法作为组件接收新props,因此抛出类型无效的错误。

解决方案

步骤1:修改常量文件,存储组件本身

把constants/drawer.js里的icon值改为组件类/函数,而非渲染好的元素:

import DashboardIcon from "@mui/icons-material/Dashboard";

export const MainMenuItems = [
  {
    label: "Dashboard",
    icon: DashboardIcon, // 直接存组件,不是<DashboardIcon />
    redirectLink: "/",
  },
];

步骤2:在渲染时传递props

在main.js中,直接使用存储的组件,并传入所需props:

import { MainMenuItems } from "../constants/drawer.js";

const MainContainer = () => {
  return (
    <>
      {MainMenuItems.map(({ label, icon: Icon }) => {
        return (
          <div key={label}> {/* 别忘了加key,避免React警告 */}
            <Icon size="small" />
            <span>{label}</span>
          </div>
        );
      })}
    </>
  );
};

可选:支持默认props

如果需要给某些图标设置默认props,同时允许渲染时覆盖,可以在常量里存储组件和默认props的对象:

// constants/drawer.js
export const MainMenuItems = [
  {
    label: "Dashboard",
    icon: {
      component: DashboardIcon,
      defaultProps: { size: "medium" }
    },
    redirectLink: "/",
  },
];

然后在渲染时合并默认props和自定义props:

// main.js
{MainMenuItems.map(({ label, icon }) => {
  const Icon = icon.component;
  return (
    <div key={label}>
      <Icon {...icon.defaultProps} size="small" /> {/* 自定义props会覆盖默认值 */}
      <span>{label}</span>
    </div>
  );
})}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 11:05:22