gpt4 book ai didi

reactjs - 在 create-react-app 项目中将 svg 作为 ReactComponent 导入时出现未定义

转载 作者:行者123 更新时间:2023-12-03 13:19:25 30 4
gpt4 key购买 nike

尝试将 svg 加载为 ReactComponent 时出现以下错误。

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 Icon.

我正在使用带有 typescript 选项的 create-react-app 来创建项目。如果我正确理解该文档,我应该能够将 svgs 作为开箱即用的 ReactComponent 导入(自 CRA2.0 起)。但奇怪的是,我对导入的组件未定义。

Adding Images, Fonts, and Files · Create React App https://facebook.github.io/create-react-app/docs/adding-images-fonts-and-files#adding-svgs

当前使用以下软件包。

    "react": "^16.8.6",
"react-dom": "^16.8.6",
"react-redux": "^6.0.1",
"react-router-dom": "^5.0.1",
"react-scripts": "^3.0.1",
"@types/node": "^12.0.0",
"@types/react": "^16.8.17",
"@types/react-dom": "^16.8.4",
"@types/react-redux": "^7.0.8",
"@types/react-router-dom": "^4.3.3",

我的代码如下。

图标.tsx

import * as React from 'react';
import { ReactComponent as IconSvg } from './IconSvg.svg';

const Icon: React.FC<IconProps> = props => {
console.log(IconSvg); // undefined
return (<IconSvg />);
};

export default Icon;

自定义.d.ts

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

tsconfig.json

{
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"baseUrl": "src",
"rootDir": "src",
"outDir": "build/dist",
"target": "es5",
"jsx": "react",
"lib": [
"es6",
"dom"
],
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"noImplicitReturns": true,
"noImplicitThis": true,
"noImplicitAny": true,
"strictNullChecks": true,
"suppressImplicitAnyIndexErrors": true,
"noUnusedLocals": false,
"allowSyntheticDefaultImports": true
},
"include": [
"src",
"custom.d.ts"
],
"exclude": [
"node_modules",
"node_scripts",
"build",
"scripts",
"acceptance-tests",
"webpack",
"jest",
"src/setupTests.ts"
]
}

如有任何建议,我们将不胜感激。

最佳答案

TLDR:import MySvg from "MySvg.svg"然后<img src={MySvg}/>

要导入 SVG:import MySvg from "MySvg.svg"这会将路径保存为 MySvg 中的字符串.

要渲染它,请使用标准 HTML 中的 img 标签,因为 MySvg实际上是一条路径:<img src={MySvg}/>

未定义的原因是您正在解构字符串。

关于reactjs - 在 create-react-app 项目中将 svg 作为 ReactComponent 导入时出现未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56672964/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com