ysj*_*sjn 6 svg reactjs create-react-app
尝试将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",
Run Code Online (Sandbox Code Playgroud)
我的代码如下。
Icon.tsx
"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",
Run Code Online (Sandbox Code Playgroud)
定制文件
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;
Run Code Online (Sandbox Code Playgroud)
tsconfig.json
declare module '*.svg' {
import React = require('react');
export const ReactComponent: React.FunctionComponent<React.SVGProps<SVGSVGElement>>;
const src: string;
export default src;
}
Run Code Online (Sandbox Code Playgroud)
任何建议表示赞赏。
Moh*_*mad -1
使用这种方式,这是一个例子,找到你的 svg 并将其放入此函数中
你的 svg 文件
interface IProps {
fill?: string;
}
export default (props: IProps) => (
<svg
style={{ marginTop: "13px" }}
fill={props.fill || Primary}
viewBox="0 0 424 424"
width={15}
>
<path d="M35,89C15,89,0,74,0,54s15-36,35-36h353c20,0,36,16,36,36s-16,35-36,35H35z" />
<path d="M388,176c20,0,36,16,36,36s-16,35-36,35H35c-20,0-35-15-35-35s15-36,35-36H388z" />
<path d="M388,335c20,0,36,15,36,35s-16,36-36,36H35c-20,0-35-16-35-36s15-35,35-35H388z" />
</svg>
);
Run Code Online (Sandbox Code Playgroud)
你想在哪里使用 svg
import React from "react";
import Menu from "./assets/svg/menu";
...
return (
...
<Menu/>
)
Run Code Online (Sandbox Code Playgroud)