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

谢谢你!


backgroundImage属性中的花括号是错误的。

可能你正在使用webpack和图像文件加载器,所以Background应该已经是一个字符串: backgroundImage: "url(" + Background + ")"

你也可以使用下面的ES6字符串模板来达到同样的效果:

backgroundImage: `url(${Background})`

还可以使用require()函数将图像引入组件。

<div style={{{\{\背景:' url(require, "images/img.svg") ' >

注意这两组花括号。第一组用于进入反应模式,第二组用于表示对象


如果您正在使用ES5 -

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

如果您正在使用ES6 -

backgroundImage: `url(${Background})`

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


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

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

你可以使用模板文字(用反标记:'…'括起来)代替。对于这样的backgroundImage属性:

backgroundImage: `url(${Background})`

你可以试试用img

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

试试这个:

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

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

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

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

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

只需添加所需的文件或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/进行转换


这对我来说很管用:

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

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

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

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


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

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

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

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


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

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


有时候你的SVG会被React内联,所以你需要在它周围加引号:

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

否则它是无效的CSS,浏览器开发工具将不会显示你已经设置了background-image。


import React, { PureComponent } from 'react'
import logo from './logo.png';

class Home extends PureComponent {
    render() {
        return (
            <div>
                 <div
                    style={{
                        backgroundImage: `url("https://www.nicesnippets.com/image/imgpsh_fullsize.png")`, backgroundRepeat: 'no-repeat', width: '800px', height: '250px', color: 'blue'
                    }}>
                        Nice Snippets
                </div>
                    <hr />
                    <div
                        style={{
                            backgroundImage: `url(${logo})`, backgroundRepeat: 'no-repeat', width: '100%', height: '250px', color: 'blue'
                        }}>
                        Nice Snippets
                </div>
            </div>
        )
    }
}

export default Home

如果你使用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/


这对我很有效

style={{backgroundImage: url(${require("../assets/pet4.jpeg").default})}}


将代码的第6行改为

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

to

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

它会起作用的。


更新至17.05.22 而不是:

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

do:

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

对于ES6,请使用

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