如何扩展样式化组件?

时间:2018-10-24 10:26:09

标签: styled-components

我有一个样式设置的组件:

interface FlexContainerProps {
    children: any;
    className?: string;
}

function FlexContainer(props: FlexContainerProps) {
    const Container = styled.div`
        display: flex;
        flex-direction: column;
        justify-content: flex-start;
    `;
    return (
        <Container className={props.className}>
            {props.children}
        </Container>
    );
}

当我在组件中使用它时,我希望能够对其进行扩展。

以下内容不起作用,因为“扩展”类的特异性较低(或者在代码中稍后出现)。

const FlexContainerExtended = styled(FlexContainer)`
    flex-direction: column-reverse;
`;

以下内容有效,但很容易破解

const FlexContainerExtended = styled(FlexContainer)`
    flex-direction: column-reverse !important;
`;

还有另一种扩展样式化组件的方法吗?

2 个答案:

答案 0 :(得分:4)

为什么要创建一个函数?您可以这样做:

const FlexContainer = styled.div`
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
 `


 const FlexContainerExtended = styled(FlexContainer)`
     flex-direction: column-reverse;
 `; 

答案 1 :(得分:0)

type FlexContainerProps = {
    className?: string,
}

const StyledFlexContainer = styled.div<FlexContainerProps>`
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
`

export const FlexContainer: React.FC<FlexContainerProps> = props => {
    return (
        <StyledFlexContainer className={props.className} 
            {props.children}
        </StyledFlexContainer>
    );
}    

在其他组件中,您可以像这样扩展FlexContainer:

const FlexContainerExtended = styled.div`
        flex-direction: column-reverse;
    `;


<FlexContainerExtended as={FlexContainer}/>