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

谢谢你!


当前回答

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

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

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

其他回答

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

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

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

这对我来说很管用:

  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

这对我很有效

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

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

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