使用React内嵌样式设置动态backgroundImage

问题描述

我对React还是陌生的,如果有人能帮助我,我将不胜感激。

我使用“ create-react-app”设置了环境,所有图像文件都位于img文件夹下的src文件夹中。组件之一动态设置背景图像。

这很好:

<div style={{ background: `url(${require("../img/file-name.jpg")}) no-repeat`}}/>

但是,当我尝试使用变量作为文件名(如下所示)时,出现错误错误:找不到模块'../img/file-name.jpg'

let imageUrl = '../img/' + filenames[0];

...

<div style={{ background: `url(${require(imageUrl)}) no-repeat`}}/>

我也尝试了以下类似的方法进行测试,但是我遇到了同样的错误

let imageUrl = '../img/file-name.jpg';

...

<div style={{ background: `url(${require(imageUrl)}) no-repeat`}}/>

我很感谢有人能帮忙!谢谢!

解决方法

有很多类似的问题,所以我不会重复我的自我,要了解为什么此代码不起作用,您应该研究Webpack的工作原理。

一个选项,它将图像移动到静态文件夹,此代码段有效:

const imageUrl = 'static/img/file-name.jpg';
<div style={{ background: `url(${require(imageUrl)}) no-repeat`}}/>

如果要从src文件夹导入,则必须事先导入(由于Webpack,文件URL在构建时已解析)。

// or use require,doesn't metter
import img1 from '../img/cat.jpg';
import img2 from '../img/dog.jpg';

const imageURL = filenames[0] === cat ? img1 : img2;
<div style={{ background: `url(${imageURL}) no-repeat`}}/>