【问题标题】: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 项目的三种方法。您可以将任一文件类型与所有三个选项一起使用。
- 导入图像并在 src 属性中使用它。
- 导入图片并在样式属性中使用。
- 动态插入到 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