问题描述
我正在尝试访问静态图像,以便在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>
);
}
}
这适用于< img>
标签。有人可以解释两者之间的区别吗?
This works for <img>
tags. Can someone explain the difference between the the two?
示例:
< img src = {Background} />
工作正常。
谢谢!
推荐答案
backgroundImage属性中的花括号是错误的。
The curly braces inside backgroundImage property are wrong.
可能你正在使用webpack和图像文件加载器,所以后台应该已经是一个字符串:
backgroundImage:url( +背景+)
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!