如何在反应样式组件中设置子组件的样式

Mar*_*vin 2 javascript reactjs styled-components

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

export const Card = styled.div`
  position: relative;
  ${props => props.horizontal && `
  ${CardImage}{
     max-height: 60%;
     overflow: hidden;
  }`}
`
export const CardImage = styled.div`
    position: relative;
`
Run Code Online (Sandbox Code Playgroud)

编辑:当我在渲染之前添加条件时,它不起作用

Cub*_*Eye 6

你几乎就在那里,你只是错过了$代码中的一个,你需要将CardImage移到Card组件上方:

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

export const Card = styled.div`
    position: relative;
    ${CardImage}{
        max-height: 60%;
        overflow: hidden;
    }
`
Run Code Online (Sandbox Code Playgroud)

编辑(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;
        }
    `}
`
Run Code Online (Sandbox Code Playgroud)