例如我有这个<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项目的三种方法。您可以同时使用这三个文件中的任何一个。
请参阅以下示例:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句