简体   繁体   English

反应:尝试为SVG创建单独的文件夹并将其导入到我的组件中,但不确定如何导入

[英]React: Trying to create separate folder for SVGs and import them into my components but unsure of how to import

I have a folder called Assets in the src directory of my application where I'm attempting to host SVGs and then import them into my components but I'm at a loss for how to do this. 我的应用程序的src目录中有一个名为Assets的文件夹,我试图在其中托管SVG,然后将其导入到我的组件中,但是我对如何执行此操作感到迷惑。 I've included my SVG file below as well as my attempt to import it into my component right beneath it. 我在下面包括了SVG文件,并尝试将其导入到其正下方的组件中。 Any help is hugely appreciated 任何帮助深表感谢

SVG file SVG文件

<svg fill="black" viewBox="0 0 320 512" height="1.5rem" width="1.5rem" xmlns="http://www.w3.org/2000/svg">
    <path d="M31.3 192h257.3c17.8 0 26.7 21.5 14.1 34.1L174.1 354.8c-7.8 7.8-20.5 7.8-28.3 0L17.2 226.1C4.6 213.5 13.5 192 31.3 192z"></path>
</svg>

Import statement in React Component trying to import SVG React Component中的import语句试图导入SVG

import {icon} from '../../assets/caretDown'

You have to import file like this including svg extension. 您必须导入这样的文件,包括svg扩展名。 For example : 例如 :

import icon from '../../assets/caretDown.svg'

You have to mention extenstion name as well. 您还必须提及扩展名称。 If you want to import multiple image then you can create one index.js file in assets folder which hold all assets image. 如果要导入多个图像,则可以在资产文件夹中创建一个index.js文件,其中包含所有资产图像。 For ex : 对于前:

import icon from 'caretDown.svg'
import iconUp from 'caretUp.svg'

Then you can export these as 然后您可以将它们导出为

export{icon,iconUp}

Then whenever you required these images somewhere in file. 然后,每当您需要这些图像在文件中的某个位置时。 You can directly import like this: 您可以像这样直接导入:

import {icon} from '../../assets/'

Ex : https://codesandbox.io/s/svg-in-react-s6u32 例如: https : //codesandbox.io/s/svg-in-react-s6u32

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

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