Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

javascript - 使用React内联样式设置backgroundImage(Setting a backgroundImage With React Inline Styles)

I'm trying to access a static image to use within an inline backgroundImage property within React.(我正在尝试访问静态图像以在React的内联backgroundImage属性中使用。)

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.(这适用于<img>标签。) Can someone explain the difference between the the two?(有人可以解释两者之间的区别吗?) Example:(例:) <img src={ Background } /> works just fine.(<img src={ Background } />很好用。) Thank you!(谢谢!)   ask by Kris translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The curly braces inside backgroundImage property are wrong.(backgroundImage属性内的花括号错误。)

Probably you are using webpack along with image files loader, so Background should be already a String: backgroundImage: "url(" + Background + ")"(可能您正在使用webpack和图像文件加载器,因此Background应该已经是一个字符串: backgroundImage: "url(" + Background + ")") You can also use ES6 string templates as below to achieve the same effect:(您还可以使用以下ES6字符串模板来达到相同的效果:) backgroundImage: `url(${Background})`

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...