使用url()方法时背景图像不工作



im试图使用background-img:url(imageLing)将图像放在背景中但不工作,检查元件background-image: url(assets/backgrounds/5.jpg);时返回给我问题是什么:这是我的代码

//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通常在部署之前捆绑您的项目,从而缩小图像并更改图像路径。因此,通过道具通过路径是行不通的。为了使图像正确加载,您必须将它们作为导入动态引用。

登录页面

//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文件选项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文件选项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;
`;

最新更新