使用CreateElement创建动态SVG React组件不起作用

发布于 2025-02-12 23:28:50 字数 1353 浏览 0 评论 0原文

在我的React应用程序中,我正在尝试构建一个图标组件Fonticon,该应该立即动态创建SVG组件。 SVG也在这里导入。

方案是在使用道具选择SVG时显示SVG。

理想的 存在选定的SVG。如果没有,则使用默认的SVG。不幸的是,我不知道为什么会收到此错误。 SVG组件是某种程度上没有构建的。

 <data:image/svg.... /> is using incorrect casing. Use PascalCase for React components, or lowercase for HTML elements.

fonticon.tsx

import React from "react";
import FasExclamationCircle from "./exclamation-circle.svg";
import FarClock from "./clock.svg";

export const iconTypes: { [key: string]: string } = {
    FarClock: FarClock,
    FasExclamationCircle: FasExclamationCircle,
};

type Props = {
    icon: string;
};

export const FontIcon: React.FC<Props> = ({ icon }) => {
    const SvgIcon = iconTypes[icon] == undefined ? FasExclamationCircle : iconTypes[icon];

    return React.createElement(SvgIcon, {
        className: "some class name",
    });
};

app.tsx(我正在使用该组件)

import FontIcon from "./FontIcon"

<div><FontIcon icon="FarClock"/></div>

PS也无法正常工作。即使我们忘记了道具逻辑

import React from "react";
import FarClock from "./clock.svg";
      

export const FontIcon: React.FC = () => {
    return React.createElement(FarClock, {
        className: "some class name",
    });
};

In my React application, I'm attempting to build an Icon Component FontIcon which should create a svg component dynamically right now. The SVGs are imported here as well.

The ideal scenario is for the svg to be displayed when a prop is used to choose an svg.

The dynamic component (FontIcon) has a list of SVGs and checks to verify if the selected SVG is present. If not, a default SVG is used. Unfortunately, and I don't know why, I receive this error. The SVG component is somehow not built.

 <data:image/svg.... /> is using incorrect casing. Use PascalCase for React components, or lowercase for HTML elements.

FontIcon.tsx

import React from "react";
import FasExclamationCircle from "./exclamation-circle.svg";
import FarClock from "./clock.svg";

export const iconTypes: { [key: string]: string } = {
    FarClock: FarClock,
    FasExclamationCircle: FasExclamationCircle,
};

type Props = {
    icon: string;
};

export const FontIcon: React.FC<Props> = ({ icon }) => {
    const SvgIcon = iconTypes[icon] == undefined ? FasExclamationCircle : iconTypes[icon];

    return React.createElement(SvgIcon, {
        className: "some class name",
    });
};

App.tsx (I am using that Component)

import FontIcon from "./FontIcon"

<div><FontIcon icon="FarClock"/></div>

p.s That is not working as well. Even if we forget the prop logic

import React from "react";
import FarClock from "./clock.svg";
      

export const FontIcon: React.FC = () => {
    return React.createElement(FarClock, {
        className: "some class name",
    });
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文