【问题标题】:How can I refer to this external image resource from JS?如何从 JS 中引用这个外部图像资源?
【发布时间】:2019-08-22 14:32:10
【问题描述】:

我有一个使用 webpack 和 sass 的 React 应用程序。我远不是这些技术的专家。应用的index.scss在顶层html元素上使用了背景图片,如下:

html {
    ...
    background-image: url('./path/to/image/file.jpg');
    ...
}

使用浏览器的开发工具,我可以看到 webpack 已经移动并重命名了图像文件:

background-image: url(http://localhost:6006/c165f4b41cec0.jpg)

现在我想在一些使用React inline styles的JS中引用相同的图像资源:

const SomeComponent = ()=> (
  <div
    style={{
      ...
      backgroundImage: ??? what goes here ???
      ...
    }}
  >
    Some text here...
  </div>
);

我怎样才能从 JS 中可靠地引用相同的图像资源,而不管 webpack 用它做什么?

我可以将内联样式转移到另一个 scss 文件中,但我不想这样做,因为我想保持这个特定的 JS 文件自包含。

谢谢。

【问题讨论】:

  • 您也可以在内联样式中使用相同的样式。只需检查图像路径即可。
  • 我尝试了backgroundImage: './path/to/image/file.jpg'backgroundImage: 'url(./path/to/image/file.jpg)',都没有被webpack替换,也没有工作,因为部署后图像在原始位置不存在...... :-(
  • 你的图片在哪里?
  • @ravibagul91, ./path/to/image/file.jpg
  • 实际上 JS 并没有使用“内联 CSS”,而是使用了稍微不同的“React 内联样式”。我更新了问题。

标签: webpack sass inline-styles


【解决方案1】:

我解决了,所以我只是在回答我自己的问题……哎呀。

import jpgFile from './path/to/image/file.jpg'; // <-- add this import

const SomeComponent = ()=> (
  <div
    style={{
      ...
      backgroundImage: 'url(' + jpgFile + ')', // or `url(${jpgFile})`
      ...
    }}
  >
    Some text here...
  </div>
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-05
    • 1970-01-01
    相关资源
    最近更新 更多