如何使用 Create React App 在 React 中导入图像(SVG 或 PNG)
How to import image(SVG or PNG) in React using Create React App
例如,我有这个 <i>
作为图标元素
<i style={{ backgroundImage: `url(${'./images/names/Mike.svg'}` }}/>
我知道我可以通过根据此单独导入图像来导入图像
但这对我来说不可行,因为我需要导入很多。
在 Create React App
中是否有解决方法可以实现这一点?
编辑:
我目前正在做这个
backgroundImage: `url(${require(`./images/names/${name}.svg`)})`
但仍然无法正常工作,除非我对名称进行硬编码
backgroundImage: `url(${require(`assets/images/names/Mike.svg`)})`
这对我来说不可行。
以下是将图像(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
例如,我有这个 <i>
作为图标元素
<i style={{ backgroundImage: `url(${'./images/names/Mike.svg'}` }}/>
我知道我可以通过根据此单独导入图像来导入图像
但这对我来说不可行,因为我需要导入很多。
在 Create React App
中是否有解决方法可以实现这一点?
编辑: 我目前正在做这个
backgroundImage: `url(${require(`./images/names/${name}.svg`)})`
但仍然无法正常工作,除非我对名称进行硬编码
backgroundImage: `url(${require(`assets/images/names/Mike.svg`)})`
这对我来说不可行。
以下是将图像(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