简体   繁体   English

如何在 React 中使用 SVG?

[英]How do I use a SVG in React?

I'm using a Typescript app I created with create-react-app, with no other dependencies other than react and react-dom.我正在使用我使用 create-react-app 创建的 Typescript 应用程序,除了 react 和 react-dom 之外没有其他依赖项。

Using the tag, how do I display an SVG?使用标签,如何显示 SVG?

I've checked that I have the right path because an adjacent PNG will render.我已经检查过我有正确的路径,因为相邻的 PNG 将呈现。 Are SVGs different? SVG 有什么不同吗?

<img src={'../assets/triangle.svg'} alt=''/>

do not use direct path link in src...import it instead and later use that reference in src.不要在 src 中使用直接路径链接...导入它,然后在 src 中使用该引用。

for example例如
import mySvg from "../asssets/triangle.svg"

then:然后:
<img src={mySvg} alt=""/>

I always like to import the SVG in the top of the file, like this:我总是喜欢在文件顶部导入SVG,像这样:

import FileSVG from "./file.svg";

and then use it as value for the src prop, like this:然后将其用作 src 道具的值,如下所示:

<img src={FileSVG} />

Make sure to check if your path it is correct too!确保检查您的路径是否也正确!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM