【问题标题】:What type to use for imported svg icon from an .svg file in React with Typescript?在 React with Typescript 中从 .svg 文件导入的 svg 图标使用什么类型?
【发布时间】:2022-01-08 06:52:23
【问题描述】:

我在assets 文件夹中有我的.svg 文件,我像这样导入它们:

import HeartIcon from 'assets/attributes/HeartIcon.svg';

然后,由于我需要将它们分配给变量,然后有条件地渲染图标,所以我有这样的东西:

const logos: LogosProps = {
  firstLogo: HeartIcon
  secondLogo: SomeOtherIcon
  thirdLogo: SomeDifferentIcon
}

当我想从这里渲染一些东西时,我要做的是:

const Logo = logos.firstLogo

return <Logo className="some class name styles" />

而且一切都很好,我只是不知道每个徽标的类型应该是什么:

interface LogosProps {
  firstLogo: React.FC 
  secondLogo: React.FC
  thirdLogo: React.FC
}

那么我应该在里面有什么类型,而不是React.FC,我尝试了React.ReactElementReact.ReactNodeReact.SVGProps&lt;SVGSVGElement&gt; 和其他一些,但它们都给了我各种错误,有些给了我没有构造函数的错误,其他我不能有className的错误,等等。

现在React.FC 我遇到的错误是:

Type '{ className: string; }' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }'.
  Property 'className' does not exist on type 'IntrinsicAttributes & { children?: ReactNode; }'.

【问题讨论】:

    标签: reactjs typescript svg


    【解决方案1】:

    typescript 之前我也遇到过同样的问题。

    ./src中创建一个名为custom.d.ts的文件,内容如下:

    declare module "*.svg" {
      const content: any;
      export default content;
    }
    

    custom.d.ts 添加到tsconfig.json 如下 您将在项目根文件夹中找到此 tsconfig.json 文件。

    "include": ["src/components", "src/custom.d.ts"]

    来源:https://webpack.js.org/guides/typescript/#importing-other-assets

    希望这能解决您的问题。

    【讨论】:

      猜你喜欢
      • 2018-03-21
      • 2018-07-31
      • 1970-01-01
      • 2017-07-06
      • 2021-02-07
      • 2020-02-19
      • 2020-10-18
      • 2017-11-22
      • 2016-11-15
      相关资源
      最近更新 更多