简体   繁体   English

React 中相同样式组件的不同背景图像

[英]Different background images for the same styled-component in React

I am using styled-components in my React Project, and I have one styled.div that I use for 2 different sections in my homepage.我在我的 React 项目中使用 styled-components,并且我有一个 styled.div 用于主页中的 2 个不同部分。 The styled component looks like this:样式化的组件如下所示:

    export const StyledContainer = styled.div`
    width: 100%;
    border-top: 1px green solid;
    margin: 10px auto;
    background-image: url(${img});
    background-size:cover;
`

Is there any way of changing the background-image without duplicating the styled component?有什么方法可以在不复制样式组件的情况下更改背景图像? To archieve different backgrounds for each section of the homepage?为主页的每个部分归档不同的背景?

You can provide props to the styled-component:您可以为样式组件提供道具

    export const StyledContainer = styled.div`
    width: 100%;
    border-top: 1px green solid;
    margin: 10px auto;
    background-image: ${props => `url(${props.img})`};
    background-size:cover;
`

And than you will use it like that:而且你会这样使用它:

<StyledContainer img="https://www.ciakroncato.com/media/productpersonalize/productpersonalize/1541242051download.jpeg" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM