作为组件动态加载svg

时间:2019-03-22 14:41:38

标签: reactjs svg components

我的问题基本上是这样的: 我有一堆svg图像都存储在这样的.js文件中

import React from 'react'

export const React = () =>
    <svg width="40" height="40" viewBox="0 0 256 256"><ellipse cx="238.456" cy="39.252" rx="28.346" ry="26.522" fill="#c90016"/></svg>

export const Angular = () =>
    <svg width="40" height="40" viewBox="0 0 256 256"><ellipse cx="238.456" cy="39.252" rx="28.346" ry="26.522" fill="#c90016"/></svg>

export const JQuery = () =>
    <svg width="40" height="40" viewBox="0 0 256 256"><ellipse cx="238.456" cy="39.252" rx="28.346" ry="26.522" fill="#c90016"/></svg>

在另一个组件中,我想基于数组渲染正确的图像,例如,我有:

import {React,Angular,JQuery} from '../svgs'
const images = [
    'React','React','JQuery','Angular','JQuery'
]

不,我想渲染每个图像,实际上是做类似的事情

<div>
images.map (image => <image>)
</div>

1 个答案:

答案 0 :(得分:1)

在再次导出命名常量svgs.js时,您必须在React中进行一些更改,以便在导入时会引发重复错误。

import React from 'react'

export const react = () =>
    <svg width="40" height="40" viewBox="0 0 256 256"><ellipse cx="238.456" cy="39.252" rx="28.346" ry="26.522" fill="#c90016"/></svg>

export const angular = () =>
    <svg width="40" height="40" viewBox="0 0 256 256"><ellipse cx="238.456" cy="39.252" rx="28.346" ry="26.522" fill="#c90016"/></svg>

export const jQuery = () =>
    <svg width="40" height="40" viewBox="0 0 256 256"><ellipse cx="238.456" cy="39.252" rx="28.346" ry="26.522" fill="green"/></svg>

之后,将它们导入您想要的位置

import {react, angular, jQuery} from '../svgs'

// don't use quotes as it represents string
// const images = [
//   'react', 'angular', 'jQuery'
// ]

const images = [
    react, angular, jQuery
]

最后在jsx中使用它们

render() {
  return (
    <div>
     // use uppercase letter for React component 
     {images.map((Image, index) => <Image key={index} />)}
    </div>
  )
}