我试图访问一个静态图像在React内的内联backgroundImage属性中使用。不幸的是,我已经不知道该怎么做了。

总的来说,我认为你是这样做的:

import Background from '../images/background_image.png';

var sectionStyle = {
  width: "100%",
  height: "400px",
  backgroundImage: "url(" + { Background } + ")"
};

class Section extends Component {
  render() {
    return (
      <section style={ sectionStyle }>
      </section>
    );
  }
}

这适用于<img>标签。有人能解释一下两者的区别吗?

例子:

<img src={Background} />工作得很好。

谢谢你!


当前回答

将代码的第6行改为

  backgroundImage: "url(" + { Background} + ")"

to

  backgroundImage: "url(" + { Background.src } + ")"

它会起作用的。

其他回答

将图像复制到React组件的文件夹中。 复制以下代码:

<div className="welcomer" style={{ backgroundImage: url(${myImage}) }}></div>

使用CSS为.welcomer指定一个高度,以便您可以看到所需大小的图像。

内联样式设置任何图像全屏:

style={{  
  backgroundImage: "url(" + "https://images.pexels.com/photos/34153/pexels-photo.jpg?auto=compress&cs=tinysrgb&h=350" + ")",
  backgroundPosition: 'center',
  backgroundSize: 'cover',
  backgroundRepeat: 'no-repeat'
}}

你可以试试用img

backgroundImage: url(process.env.PUBLIC_URL + "/      assets/image_location")

试试这个:

style={{ backgroundImage: `url(require("path/image.ext"))` }}

只需添加所需的文件或url

<div style={
   {
      backgroundImage: `url(${require("./path_local")})`,      
   }
}
>

或者在css中设置base64 image

div {
  background:
    url('data:image/gif;base64,R0lGODlhZQBhAPcAACQgDxMFABsHABYJABsLA')
    no-repeat
    left center;
}

您可以使用https://www.base64-image.de/进行转换