tak*_*uma 4 inline require reactjs
我是 React 新手,如果有人能提供帮助,我将不胜感激......
我使用“create-react-app”设置环境,所有图像文件都位于文件夹img下的src文件夹中。其中一个组件动态设置背景图像。
这工作正常:
<div style={{ background: `url(${require("../img/file-name.jpg")}) no-repeat`}}/>
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试使用变量作为文件名(如下所示)时,出现错误:错误:找不到模块“../img/file-name.jpg”
let imageUrl = '../img/' + filenames[0];
...
<div style={{ background: `url(${require(imageUrl)}) no-repeat`}}/>
Run Code Online (Sandbox Code Playgroud)
我也尝试了类似下面的测试,但我得到了同样的错误。
let imageUrl = '../img/file-name.jpg';
...
<div style={{ background: `url(${require(imageUrl)}) no-repeat`}}/>
Run Code Online (Sandbox Code Playgroud)
如果有人可以提供帮助,我将不胜感激!谢谢你!
有很多类似的问题,所以我不会重复自己,要理解为什么这段代码不起作用,你应该研究 Webpack 的工作原理。
一种选择是将图像移动到静态文件夹,此代码片段是有效的:
const imageUrl = 'static/img/file-name.jpg';
<div style={{ background: `url(${require(imageUrl)}) no-repeat`}}/>
Run Code Online (Sandbox Code Playgroud)
如果您想从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`}}/>
Run Code Online (Sandbox Code Playgroud)