样式化组件中的背景图像反应 [英] background image in styled components react

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

问题描述

晚上好.

在将react与样式化组件结合使用时,我遇到了一个问题.

I am facing an issue while using react in combination with styled components.

我在中有一个图像文件夹:

I have an image folder located in :

我的样式组件位于以下文件夹中:

And I have my styled components in the following folder :

在样式化组件内部,我试图像这样导入图像:

Inside the styled components I'm trying to import the image like this :

const FormImage = styled.div`
    width: 150px;
    height: 150px;
    margin: 0 auto;
    margin-top: -20%;
    background-image: url(../../img/testlogo.png);
`;

我确定这是正确的路径.但是以某种方式,该图像没有显示在浏览器中.

Im sure this is the right path. But somehow the image is not showing in the browser.

这是我在浏览器中看到的:

This is what i'm seeing in my browser :

推荐答案

这种路径在运行时不可用(因为CSS-in-JS之类的 styled-component 在运行时创建了CSS,是没有运行时的解决方案),则应尝试以下方法之一:

Such path is not available in runtime (as CSS-in-JS like styled-component creates the CSS in runtime, although there are solutions with no-runtime), you should try one of the next approaches:

import ImgSrc from '../../img/testlogo.png';
const FormImage = styled.div`
    background-image: url(${ImgSrc});
`;

// or
const FormImage = styled.div`
    background-image: url(${require(`../../img/testlogo.png`)});
`;

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

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