【问题标题】:How to import image(SVG or PNG) in React using Create React App如何使用 Create React App 在 React 中导入图像(SVG 或 PNG)
【发布时间】:2020-12-17 04:23:50
【问题描述】:

例如我有这个<i> 用于图标元素

<i style={{ backgroundImage: `url(${'./images/names/Mike.svg'}` }}/>

我知道我可以根据post单独导入图片来导入图片

但在我的情况下这是不可行的,因为我需要导入很多。

Create React App 中是否有解决方法可以实现这一点?

编辑: 我目前正在这样做

backgroundImage: `url(${require(`./images/names/${name}.svg`)})`

但仍然无法正常工作,除非我对名称进行硬编码

backgroundImage: `url(${require(`assets/images/names/Mike.svg`)})`

这在我的情况下是不可行的。

【问题讨论】:

标签: javascript reactjs typescript create-react-app


【解决方案1】:

以下是将图像(SVG 和 PNG)导入 React 项目的三种方法。您可以将任一文件类型与所有三个选项一起使用。

  1. 导入图像并在 src 属性中使用它。
  2. 导入图片并在样式属性中使用。
  3. 动态插入到 require 函数中。

请看下面的例子:

import React from 'react';
import backgroundImg from '../assets/images/background.png';
import logoImg from '../assets/images/logo.svg';

const Test = props => {

     const imageLink = 'another.png'
     // const imageLink = props.image
     // You can loop this component in it's parent for multiple images.

     return (
         <div>
              <img src={logoImg} style={{ width: '200px', height: '45px' }} />
              <div style={{ width: '100%', height: '100%', backgroundImage: `url(${backgroundImg})`, backgroundRepeat: 'no-repeat', backgroundPosition: 'center', backgroundSize: 'cover', position: 'fixed'}} />
              <img width={900} height={500} alt="test img"  src={require(`../assets/images/${imageLink}`)}/>
         </div>
     )
}

export default Test

【讨论】:

  • 如果需要导入300张图片怎么办?
  • 我在上面添加了第三个选项,可能会满足您的需求。
猜你喜欢
  • 2020-07-31
  • 2017-10-05
  • 1970-01-01
  • 2017-11-20
  • 2023-03-17
  • 2021-07-23
  • 2019-01-10
  • 1970-01-01
  • 2019-12-09
相关资源
最近更新 更多