【问题标题】:TypeScript SVG import as a React Component - Element type is invalid: expected a string (for built-in components) or a class/functionTypeScript SVG 导入为 React 组件 - 元素类型无效:应为字符串(用于内置组件)或类/函数
【发布时间】:2021-07-18 20:26:09
【问题描述】:

我正在尝试将 svg 作为 React 组件导入。我已经安装了svgr。我还添加了 svg 类型定义:

declare module '*.svg' {
    import React = require('react');
    export const ReactComponent: React.FunctionComponent<React.SVGProps<SVGSVGElement>>;
    const src: string;
    export default src;
}

以上内容也包含在我的tsconfig.json

当我尝试导入 svg 时:

import { ReactComponent as Logo }  from "logo.svg";

// inside render
return <Logo/>

它抛出:

Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports

非常感谢任何帮助!

【问题讨论】:

  • 为什么要导出像component这样的SVG文件?以及你如何使用Logo
  • @Viet:否则打字稿不知道如何导入&lt;Logo/&gt;

标签: reactjs typescript svg webpack


【解决方案1】:

如果你想使用.svg。你就这样用吧。

import Logo from "logo.svg";

//内部渲染

<img src={Logo} />

【讨论】:

  • 嗨。我实际上想将 svg 嵌入到我的 HTML 中。您建议的方式将向服务器发出多个请求。
猜你喜欢
  • 2017-12-07
  • 1970-01-01
  • 1970-01-01
  • 2022-06-13
  • 1970-01-01
  • 1970-01-01
  • 2019-01-29
  • 2019-01-16
相关资源
最近更新 更多