问题
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