[英]react inline style backgroundImage not shown
I am trying to load a background image in a react component.我正在尝试在反应组件中加载背景图像。 The image will ultimately vary so I am doing this with an inline style as follows:
图像最终会有所不同,因此我使用内联样式执行此操作,如下所示:
const imageFilename = '../../../assets/img/picture.jpg';
<div className="auth-page" style={{backgroundImage: `url(${imageFilename}` , backgroundColor: '#cccccc'}}>
In chrome devtools I can see the style element which looks correct but no file is visible - I do see the background color though.在 chrome devtools 中,我可以看到看起来正确但没有文件可见的样式元素 - 我确实看到了背景颜色。
element.style {
background-image: url(../../../assets/img/picture.jpg);
background-color: rgb(204, 204, 204);
}
If I use a normal css file with background-image using the same path and filename the image is shown:如果我使用具有相同路径和文件名的背景图像的普通 css 文件,则会显示图像:
.auth-page {
padding-top: 10vh;
height: 100vh;
background-image: url(../assets/img/full-screen-image-5.jpg);
background-color: #cccccc;
}
Why does this not work using inline style (I remove background-image and background-color from the auth-page css style)?为什么使用内联样式不起作用(我从 auth-page css 样式中删除了背景图像和背景颜色)?
Problem:问题:
You are missing )
here: url(${imageFilename}
你错过了
)
这里: url(${imageFilename}
Try:尝试:
import Img from '../../../assets/img/picture.jpg';
<div className="auth-page" style={{backgroundImage: `url(${Img})` , backgroundColor: '#cccccc'}}>
First Problem第一个问题
Width and height have to be given along with the background image when the background image shows.当背景图像显示时,宽度和高度必须与背景图像一起给出。
Second Problem第二个问题
You are missing ) here: backgroundImage: url(${imageFilename}
你在这里失踪了): backgroundImage:
url(${imageFilename}
Demo:-演示:-
const imageFilename = ../../../assets/img/picture.jpg';
<div className="auth-page" style={{backgroundImage: `url(${imageFilename})` , backgroundColor: '#cccccc', width: "100%", height: "100vh"}}></div>
You need to import the image.您需要导入图像。
import imageFilename from '../../../assets/img/picture.jpg';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.