[英]Importing multiple SVG via name in a react-native component
I am trying to fetch multiple icons from assets/Icons folder where I have placed multiple icons as svgs I want to load the svg by passing name.我正在尝试从 assets/Icons 文件夹中获取多个图标,我在其中放置了多个图标作为 svg,我想通过传递名称加载 svg。
I am able to get the icon by我可以通过
import CustomIcon from '../assets/Icons/icon-account.svg';
<View>
<CustomIcon/>
</View>
but i can't keep writing multiple imports for each and every icon I need.但我不能继续为我需要的每个图标编写多个导入。
is there a way I can get the required icons by passing name as a prop to有没有办法通过将名称作为道具传递给
example例子
import CustomIcon from '../assets/Icons';
<View>
<CustomIcon name='icon-account.svg'/>
</View>
Is there anyway so that I can get the above code working?无论如何,我可以让上面的代码工作吗?
Why don't you import them all into a central file为什么不将它们全部导入中央文件
import AccountIcon from '../assets/Icons/icon-account.svg';
import GearIcon from '../assets/Icons/icon-gear.svg';
export default {
AccountIcon,
GearIcon
}
And then import that central file elsewhere?然后将该中心文件导入其他地方?
If you are looking to conditionally render a.svg file by passing a prop to the component, you can do this:如果您希望通过将 prop 传递给组件来有条件地渲染 a.svg 文件,您可以这样做:
Let's say you have a few flags and you'd like to render svg images given the country name.假设您有一些标志,并且您想在给定国家名称的情况下渲染 svg 图像。
import React from 'react';
import Austria from '../../assets/NationalTeams/austria.svg';
import Belgium from '../../assets/NationalTeams/belgium.svg';
import Croatia from '../../assets/NationalTeams/croatia.svg';
...
const flags = {
Austria: Austria,
Belgium: Belgium,
Croatia: Croatia,
...
}
// See: https://reactjs.org/docs/jsx-in-depth.html#choosing-the-type-at-runtime
export default function Flag(props) {
const CountryFlag = flags[props.country];
return <CountryFlag width={30} height={30} />;
}
2.Then import this component whenever you need to render a.svg image and pass the country prop as defined in flags object. 2.然后在需要渲染.svg 图像并传递标志 object 中定义的国家/地区属性时导入此组件。
import Flag from '../../Flag.js';
...
// will render Austria flag
<Flag country={'Austria'} />
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.