【问题标题】:Setting a dynamic backgroundImage With React inline styles使用 React 内联样式设置动态 backgroundImage
【发布时间】:2021-01-29 16:29:36
【问题描述】:

我是 React 新手,如果有人可以提供帮助,我将不胜感激......

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

这很好用:

<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`}}/>

如果有人可以提供帮助,我将不胜感激!谢谢!

【问题讨论】:

  • 这是因为 require 使用路径,当你分隔路径时, required 会读取该值,但它会将其视为字符串并将 .. 或 ./ 作为字符串字符而不是路径分隔符。

标签: reactjs inline require


【解决方案1】:

有很多类似的问题,所以我不会重复我自己,要理解为什么这段代码不起作用,你应该研究一下 Webpack 是如何工作的。

一个选项是将图像移动到静态文件夹,这个 sn-p 是有效的:

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

如果你想从src文件夹中导入,你必须提前导入if(由于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`}}/>

【讨论】:

  • 非常感谢!我最终使用了静态文件夹。
猜你喜欢
  • 2021-05-18
  • 2011-10-03
  • 2021-01-09
  • 1970-01-01
  • 2016-12-11
  • 2019-03-27
  • 1970-01-01
相关资源
最近更新 更多