我正在尝试设置样式化组件的子组件的样式,但是它将CSS发送给父组件而不是子组件/这是我的代码,

export const Card = styled.div`
  position: relative;
  ${props => props.horizontal && `
  ${CardImage}{
     max-height: 60%;
     overflow: hidden;
  }`}
`
export const CardImage = styled.div`
    position: relative;
`

编辑:当我在渲染之前添加条件时,那是行不通的

最佳答案

您快要准备好了,只是在代码中缺少$,您需要将CardImage移动到Card组件上方:

export const CardImage = styled.div`
    position: relative;
`

export const Card = styled.div`
    position: relative;
    ${CardImage}{
        max-height: 60%;
        overflow: hidden;
    }
`

编辑(04/04/2018):

如果要像您一样在整个块周围添加条件,则需要从样式化的组件中导入css函数,并使用该函数:
import styled, {css} from "styled-components";

export const CardImage = styled.div`
    position: relative;
`

export const Card = styled.div`
    position: relative;

    ${props => props.horizontal && css` // - Notice the css` here.
        ${CardImage}{
            max-height: 60%;
            overflow: hidden;
        }
    `}
`

09-18 12:46