简体   繁体   English

React 中的内联背景图像

[英]Inline background-image in React

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 /src folder 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!任何帮助将不胜感激!

I figured it out, you can't just put a link straight into url.我想通了,您不能将链接直接放入 url。 You need to require it first.你需要先require它。

var bg=require('../../../../images/products/cards/main.jpg')
return (      
  <div className="ProductItem">

      {/* Background Image */}
      <div className='background-image' style ={ { backgroundImage: "url("+bg+")" } }></div>

Hello你好

Everybody after some Research I found a better solution for 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是使用它的最佳方式

 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当它们无法加载时,我们需要要求它们

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 +")" }}>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM