【问题标题】:Problem with using SVG files as ReactComponent in Gatsby project在 Gatsby 项目中使用 SVG 文件作为 ReactComponent 的问题
【发布时间】:2020-06-17 00:39:32
【问题描述】:

我正在尝试在我的 Gatsby.js 项目中包含 svg 文件。

LogoIcon 组件是这样的:

import React from 'react';
import { ReactComponent as LogoInstagram } from '../assets/img/instagram-logo.svg';

const LogoIcon = () => {
  return (
    <div>
      {}
      <LogoInstagram />
    </div>
  );
};

export default LogoIcon;

我收到此错误:

Error: Element 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.

Check the render method of `LogoIcon`.
▶ 20 stack frames were collapsed.
(anonymous function)
/website/.cache/app.js:67
  64 | const preferDefault = m => (m && m.default) || m
  65 | let Root = preferDefault(require(`./root`))
  66 | domReady(() => {
> 67 |   renderer(<Root />, rootElement, () => {
  68 |     apiRunner(`onInitialClientRender`)
  69 |   })
  70 | })

它与 SVG 文件有关还是我遗漏了什么?

【问题讨论】:

    标签: reactjs svg gatsby


    【解决方案1】:

    有几个步骤可以让它工作:

    1. 安装gatsby-plugin-react-svg

    2. 将其包含在您的 gatsby-config.js 文件中:

    module.exports = {
      plugins: [
       ...
       `gatsby-plugin-react-svg`,
       ...
      ]
    }
    
    1. 如果您已经这样做了,只需在不带大括号的情况下导入它:
    // import name doesn't matter
    import LogoInstagram from '../assets/img/instagram-logo.svg';
    
    1. 将其用作常用组件:
    <div>
       <LogoInstagram />
    </div>
    

    【讨论】:

    • 将 { ReactComponent as LogoInstagram } 更改为 LogoInstagram 有效。非常感谢。
    • 我们应该使用什么类型?
    • 我注意到如果你尝试在 global.d.ts 上定义类型 // 修复 typescript 无法导入 svgs 的错误 has react components declare module "*.svg" { import React = 要求(“反应”); export const ReactComponent:React.FunctionComponent & { title?: string |不明确的; }> 常量源代码:字符串;导出默认src; } 你得到一个错误:类型 '{ className: string; }' 不可分配给类型“IntrinsicAttributes”。类型“IntrinsicAttributes”上不存在属性“className”。
    • 解决方案:声明模块 "*.svg" { const content: any;导出默认内容; }
    • @RoyerAdames 大声笑我刚刚发布了相同的解决方案:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-22
    • 1970-01-01
    相关资源
    最近更新 更多