[英]background-image is not working when using url() method?
im trying to put image in the background by using background-img:url(imageLing)
but not working and it's return to me when inspect the element background-image: url(assets/backgrounds/5.jpg);
我试图通过使用
background-img:url(imageLing)
将图像放在后台但不工作,当检查元素background-image: url(assets/backgrounds/5.jpg);
它返回给我what is the issue: this is my code问题是什么:这是我的代码
//login page
<LoginWrapper img={`assets/backgrounds/${randomImage}.jpg`}>
<Wrapper>
<LoginForm onClickLogin={login} />
</Wrapper>
</LoginWrapper>
//css file using styled- components
interface LoginProps {
img: string;
}
export const LoginWrapper = styled.div<LoginProps>`
display: flex;
align-items: center;
justify-content: center;
height: 93vh;
background-image: url(${({ img }) => img});
background-size: cover;
background-repeat: no-repeat;
`;
React generally bundles your project before deployment which minifies images and changes image path. React 通常会在部署之前捆绑您的项目,这会缩小图像并更改图像路径。 Hence, passing the path via props will not work.
因此,通过 props 传递路径将不起作用。 In order to get images to load properly, you have to reference them dynamically as an import.
为了使图像正确加载,您必须将它们作为导入动态引用。
Login Page登录页面
//login page
import img from './assets/backgrounds/bg.gif'; // <= update this path according to your folder structure, i've added this path as an example
<LoginWrapper img={img}>
<Wrapper>
<LoginForm onClickLogin={login} />
</Wrapper>
</LoginWrapper>
CSS File Option 1 (using img from props) CSS 文件选项 1(使用道具中的 img)
//css file using styled- components
// interface LoginProps {
// img: string;
// }
export const LoginWrapper = styled.div`
display: flex;
align-items: center;
justify-content: center;
height: 93vh;
background-image: url(${({ img }) => img});
background-size: cover;
background-repeat: no-repeat;
`;
CSS File Option 2 (importing image in this file itself) CSS 文件选项 2(在此文件本身中导入图像)
//css file using styled- components
import img from './assets/backgrounds/bg.gif'; // <= update this path according to your folder structure, i've added this path as an example
export const LoginWrapper = styled.div`
display: flex;
align-items: center;
justify-content: center;
height: 93vh;
background-image: url(${img});
background-size: cover;
background-repeat: no-repeat;
`;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.