background image in styled components react

心已入冬 提交于 2021-02-08 11:08:33

问题


Good evening.

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 :


回答1:


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`)});
`;


来源:https://stackoverflow.com/questions/59164033/background-image-in-styled-components-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!