使用样式组件更改背景图像 [英] Change background image with styled-component

查看:26
本文介绍了使用样式组件更改背景图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想动态更改背景图像,当我尝试按照它进行操作时,它不起作用,但是当我在 chrome 中打开 devtools 时,可以显示该背景

I want to change the backgroundImage dynamiclly, when i try it follow as, it did not work,but when i open the devtools in chrome, can show that background

<RecommendWrapper>
     <RecommendItem imgUrl="../../static/banner.png" >
     </RecommendItem>  
</RecommendWrapper>

export const RecommendItem = styled.div`
    width: 280px;
    height: 50px;
    background-size: contain;
    background: url(${(props)=>props.imgUrl});  
`;

如果我这样使用,它可以工作,但不能改变图像动态.

if i use like this,it can work,but can't change image dynamic.

import banner from "../../statics/banner.png"
export const RecommendItem = styled.div`
    width: 280px;
    height: 50px;
    background-size: contain;
    background:url(${banner}); 
`;

如果我使用网络图片(网址喜欢​​https://syean.cn/img/avatar.jpg") ,它也可以工作

and if i use a network image(url likes "https://syean.cn/img/avatar.jpg") ,it also can work

推荐答案

将您的文件移动到公共文件夹中并尝试以下命令:

Move your file in public folder and try this command:

<RecommendItem imgUrl={process.env.PUBLIC_URL + '/banner.png'} >

这篇关于使用样式组件更改背景图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆