React Material UI图标的动态导入遇到问题
P粉627136450
P粉627136450 2023-08-31 09:14:27
[React讨论组]

你好,我正在尝试从mui动态加载图标,以下是代码:

import React from "react";
import * as MuiIcons from "@mui/icons-material";
console.log("MuiIcons: ", MuiIcons);

const Icon = ({ iconName }) => {
        return <div>{MuiIcons[iconName]}</div>;
};

export default Icon;

但是我得到了以下错误:

react-dom.development.js:14887 Uncaught Error: Objects are not valid as a React child (found: object with keys {$$typeof, type, compare}). If you meant to render a collection of children, use an array instead.
    at throwOnInvalidObjectType (react-dom.development.js:14887:9)
    at reconcileChildFibers2 (react-dom.development.js:15828:7)
    at reconcileChildren (react-dom.development.js:19167:28)
    at updateHostComponent (react-dom.development.js:19924:3)
    at beginWork (react-dom.development.js:21618:14)
    at HTMLUnknownElement.callCallback2 (react-dom.development.js:4164:14)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:16)
    at invokeGuardedCallback (react-dom.development.js:4277:31)
    at beginWork$1 (react-dom.development.js:27451:7)
    at performUnitOfWork (react-dom.development.js:26557:12)

有任何解决办法吗?提前谢谢你。

P粉627136450
P粉627136450

全部回复(1)
P粉198670603

您正在导入一个对象而不是一个React组件。

要以这种方式使用它,您可以这样做:

const Icon = ({ iconName }) => {
  const Icon = MuiIcons[iconName]
  return <Icon />
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号