如何在 React styled-components 中设置子组件的样式

How to style child components in react 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;
`

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

const StyledCard = styled.div`
   //parent styles goes here
`;
const StyledImage = styled.img`
   //image styles
`;

class CardImage extends Component {
   render() {
     return <StyledImage/>
}

export default class Card extends Component {
  render() {
    return <StyledCard>
               <CardImage/>
           </StyledCard>
  }
}

它应该适合你吗?

就快完成了,您只是在代码中缺少一个 $,您需要将 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;
        }
    `}
`