【问题标题】:Dynamically load svgs as components in react在反应中动态加载 svgs 作为组件
【发布时间】:2019-08-13 14:04:47
【问题描述】:

我的问题基本上是这样的: 我有一堆 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>

【问题讨论】:

    标签: reactjs svg components


    【解决方案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>
      )
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-14
      • 2018-03-17
      • 2016-10-10
      • 2019-10-27
      • 1970-01-01
      • 2017-01-01
      • 1970-01-01
      相关资源
      最近更新 更多