Javascript React 中的内联背景图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45806899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Inline background-image in React
提问by Gage Hendy Ya Boy
I am trying to set a background image via inline styles in React.
我正在尝试通过 React 中的内联样式设置背景图像。
After looking through a few posts this one's solution worked for me:
在浏览了一些帖子后,这个解决方案对我有用:
<div className="phase1" style ={ { backgroundImage: "url('https://lh3.googleusercontent.com/MOf9Kxxkj7GvyZlTZOnUzuYv0JAweEhlxJX6gslQvbvlhLK5_bSTK6duxY2xfbBsj43H=w300')" } }>
I pasted that directly into my component without changing the link just to test it, and it worked. But now that I am trying to reference an image from my /srcfolder it isn't working.
我将它直接粘贴到我的组件中,而没有更改链接只是为了测试它,并且它起作用了。但是现在我试图从我的/src文件夹中引用图像它不起作用。
<div className='background-image' style ={ { backgroundImage: "url('../../../../images/products/cards/main.jpg')" } }>asdfasdfasdfasdf</div>
Nothing shows up and I am not getting any error or warning.
没有任何显示,我没有收到任何错误或警告。
Any help would be really appreciated!
任何帮助将非常感激!
回答by Gage Hendy Ya Boy
I figured it out, you can't just put a link straight into url. You need to requireit first.
我想通了,您不能将链接直接放入 url。你require首先需要它。
var bg=require('../../../../images/products/cards/main.jpg')
return (
<div className="ProductItem">
{/* Background Image */}
<div className='background-image' style ={ { backgroundImage: "url("+bg+")" } }></div>
回答by Klod Lala
const Images = [
require('./greenbanner.jpg'),
require('./greengrass.jpeg'),
require('./opengreen.jpg') ];
This is for an array of images that should be required
we need to require them when they cannot be loaded
这是用于应该需要的图像数组,
我们需要在无法加载它们时要求它们
回答by Masud Rana
I hope Background Img is very common. So please try to use it. It is very easy to use. At first you should import img and then easily use it in your jxs file.
我希望背景图片很常见。所以请尝试使用它。这是非常容易使用。首先你应该导入 img 然后在你的 jxs 文件中轻松使用它。
import InnerBgImg from "../../assets/static/img/banner/inner_banner_bg_static.jpg";
return (
<div className="inner_banner" style={{ backgroundImage: "url(" + InnerBgImg +")" }}>
回答by Masud Rana
Hello
你好
Everybody after some Research I found a better solution for i=this question like this
大家经过一番研究后,我找到了一个更好的解决方案 i=this question like this
import BannerBgImg1 from "../../assets/static/img/banner/banner_bg_img_1.jpg";
<div className="bannerInnerItem" style={{backgroundImage: `url(${BannerBgImg1})` }}>
is the best way to use this
是使用它的最佳方式

