本文介绍了使用 React 内联样式设置 backgroundImage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试访问静态图像以在 React 的内联 backgroundImage 属性中使用.不幸的是,我已经不知道如何做到这一点.

I'm trying to access a static image to use within an inline backgroundImage property within React. Unfortunately, I've run up dry on how to do this.

一般来说,我认为你只是做了如下:

Generally, I thought you just did as follows:

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>
    );
  }
}

这适用于 标签.有人能解释一下两者的区别吗?

This works for <img> tags. Can someone explain the difference between the two?

示例:

<img src={ Background }/> 工作得很好.

谢谢!

推荐答案

backgroundImage 属性中的花括号错误.

The curly braces inside backgroundImage property are wrong.

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

Probably you are using webpack along with image files loader, so Background should be already a String:backgroundImage: "url(" + Background + ")"

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

You can also use ES6 string templates as below to achieve the same effect:

backgroundImage: `url(${Background})`

这篇关于使用 React 内联样式设置 backgroundImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 23:48