尝试将 svg 加载为 ReactComponent 时出现以下错误。
元素类型无效:应为字符串(对于内置组件)或类/函数(对于复合组件)但得到:未定义。您可能忘记从定义组件的文件中导出组件,或者您可能混淆了默认导入和命名导入。
检查 的渲染方法
Icon
。
我正在使用带有typescript选项的 create-react-app 来创建项目。如果我正确理解了文档,我应该能够立即将 svgs 作为 ReactComponent 导入(从 CRA2.0 开始)。但奇怪的是,我对导入的组件没有定义。
添加图像、字体和文件 · 创建 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;
}
配置文件
{
"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"
]
}
任何建议表示赞赏。