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

谢谢你!


当前回答

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

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

其他回答

更新至17.05.22 而不是:

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

do:

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

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

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

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

backgroundImage: `url(${Background})`

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

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

这对我来说很管用:

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