如何从 JS 中引用此外部图像资源? [英] How can I refer to this external image resource from JS?
问题描述
我有一个使用 webpack 和 sass 的 React 应用程序.我远不是这些技术的专家.应用程序的 index.scss
在顶级 html 元素上使用背景图像,如下所示:
html {...背景图片:url('./path/to/image/file.jpg');...}
使用浏览器的开发工具我可以看到 webpack 已经移动并重命名了图像文件:
background-image: url(http://localhost:6006/c165f4b41cec0.jpg)
现在我想在一些使用 的 JS 中引用相同的图像资源反应内联样式:
const SomeComponent = ()=>();
如何从 JS 稳健地引用相同的图像资源,而不管 webpack 用它做什么?
我可以将内联样式转移到另一个 scss 文件中,但我不想这样做,因为我想保持这个特定的 JS 文件自包含.
谢谢.
解决方案 我已经解决了,所以我只是在回答我自己的问题...... yuk.
import jpgFile from './path/to/image/file.jpg';//<-- 添加这个导入const SomeComponent = ()=>();
I have a React app which uses webpack and sass. I am far from being an expert on any of these technologies. The app's index.scss
uses a background image on the top-level html element, as follows:
html {
...
background-image: url('./path/to/image/file.jpg');
...
}
Using the browser's dev tools I can see that webpack has moved and renamed the image file:
background-image: url(http://localhost:6006/c165f4b41cec0.jpg)
Now I want to refer to the same image resource in some JS which uses React inline styles:
const SomeComponent = ()=> (
<div
style={{
...
backgroundImage: ??? what goes here ???
...
}}
>
Some text here...
</div>
);
How can I robustly refer to the same image resource from JS, regardless of what webpack does with it?
I could transfer the inline style into another scss file, but I would prefer not to as I want to keep this particular JS file self-contained.
Thanks.
解决方案 I worked it out, so I'm just answering my own question... yuk.
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>
);
这篇关于如何从 JS 中引用此外部图像资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文