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

谢谢你!


当前回答

对于ReactJS中的本地文件。 试一试

import Image from "../../assets/image.jpg";

<div
style={{ backgroundImage: 'url(' + Image + ')', backgroundSize: 'auto' }}
>Hello
</div>

这就是带有内联样式的ReactJS的情况,其中Image是一个本地文件,必须用路径导入。

其他回答

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

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

你可以试着在整个url上添加反引号

风格= {{backgroundImage: url(${瓦尔。image || 'http://max-themes.net/demos/grandtour/upload/Tokyo_Dollarphotoclub_72848283-copy-700x466.jpg'})

如果你使用webpack,你需要编辑webpack.config.js和 把这个加进去

module: {
  rules: [
 {
      test: /\.(png|jpe?g|gif)$/i,

     dependency: { not: ['url'] },
      use: [
        {
          loader: 'url-loader',
          options: {
            limit: 8192,
          },
        },
      ],
    },
  ],
}

如果你使用文件加载器来渲染图像,你需要像下面这样删除它:

    {
       test: /\.(png|jpe?g|gif)$/i,
       loader: 'file-loader',
    },

在CSS文件中,不要使用background-image,而是使用background:

background: url(Background);

有关webpack与图像的更多信息,请参见此: https://v4.webpack.js.org/loaders/url-loader/

这对我来说很管用:

  import Background from '../images/background_image.png';
    
  <div className=...
       style={{
              background: `url(${Background})`,
            }}
    >...</div>

将代码的第6行改为

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

to

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

它会起作用的。