我试图访问一个静态图像在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} />工作得很好。

谢谢你!


当前回答

你可以试试用img

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

其他回答

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

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'
}}

如果您正在使用ES5 -

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

如果您正在使用ES6 -

backgroundImage: `url(${Background})`

基本上删除不必要的花括号,同时为backgroundImage属性工作增加值将工作。

试试这个,对我来说很管用

backgroundImage: `url("${Background}")`

对于ES6,请使用

backgroundImage: `url("${Background}")

对我来说,有效的方法就是这样

style={{ backgroundImage: `url(${require("./resources/img/banners/3.jpg")})` }}