样式组件:如何选择子组件?

时间:2018-01-23 07:33:25

标签: javascript reactjs styled-components

// card.js

import styled from 'styled-components'
const Heading = styled.h1`
    color: red;
`;

const Summary = styled.p`
    text-align: center;
`;

const Card = ({className, heading, summary}) => (
    <div className={className}>
        <Heading>{heading}</Heading>
        <Summary>{summary}</Summary>
    </div>
);

export default Card;

// cardWithBlueHeading.js

import styled from 'styled-components';
import Card from './card.js';

const CardWithBlueHeading = styled(Card)`
    // How can I select the Heading component and make it blue?
`;

export default CardWithBlueHeading;

我试图改变子组件的样式。这些风格可能是一次性的。我试图避免选择HTML元素h1和伪选择器。

2 个答案:

答案 0 :(得分:3)

您可以将道具传递给如下所示的样式组件:

import styled from 'styled-components'
const Heading = styled.h1`
    color: ${props => props.color};
`;

将颜色作为道具传递

<Heading color='blue'/>

答案 1 :(得分:0)

您可以将标题设为className属性,然后使用

选择它
const CardWithBlueHeading = styled(Card)`
  > .[classNameYouGive] {
    background: blue;
  }
`;

这是标准的CSS方式。