[英]React SVG tag name provided is not valid
I'm attempting to add an SVG to a React app (built with create-react-app).我正在尝试将 SVG 添加到 React 应用程序(使用 create-react-app 构建)。 When I try to add it as a component, I get an error like this:
当我尝试将其添加为组件时,出现如下错误:
InvalidCharacterError: Failed to execute 'createElement' on 'Document': The tag name provided ('/static/media/logo.8d229b2c.svg') is not a valid name.
What am I missing?我错过了什么?
Code:代码:
import React from 'react';
import Logo from '../img/logo.svg';
const Header = () => {
return (
<div>
<Logo />
</div>
)
}
export default Header;
You can import it this way:您可以通过以下方式导入它:
import { ReactComponent as Logo } from '../img/logo.svg';
as said in CRA (create-react-app) documentation如 CRA (create-react-app) 文档中所述
an render it the way you want:以您想要的方式渲染它:
import React from 'react';
import { ReactComponent as Logo } from '../img/logo.svg';
const Header = () => {
return (
<div>
<Logo />
</div>
)
}
And also, if it's not necessary to render it as a component, you could just render your svg as an image this way:此外,如果不需要将其渲染为组件,您可以通过以下方式将 svg 渲染为图像:
import React from 'react';
import logo from '../img/logo.svg';
const Header = () => {
return (
<div>
<img src={logo} alt="logo"/>
</div>
)
}
export default Header;
You need to import the component using this syntax:您需要使用以下语法导入组件:
import { ReactComponent as Logo } from '../img/logo.svg';
Using the curly braces and ReactComponent
is necessary - they tell React that you want to build a component with the SVG.使用花括号和
ReactComponent
是必要的——它们告诉 React 你想用 SVG 构建一个组件。
I only found this because of a Dan Abramov reply to a create-react-app issue.我发现这个只是因为 Dan Abramov 对 create-react-app 问题的回复。 The link he posted in his comment no longer works, but it's still mentioned in the docs.
他在评论中发布的链接不再有效,但文档中仍然提到它。
https://github.com/facebook/create-react-app/issues/5293 https://github.com/facebook/create-react-app/issues/5293
https://create-react-app.dev/docs/adding-images-fonts-and-files/ https://create-react-app.dev/docs/adding-images-fonts-and-files/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.