【问题标题】:How to extend styled components?如何扩展样式组件?
【发布时间】:2019-03-28 17:29:45
【问题描述】:

我有一个样式组件:

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;
`;

以下工作但很hacky:

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

还有其他方法可以扩展样式组件吗?

【问题讨论】:

    标签: styled-components


    【解决方案1】:

    你可以这样做:

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

    【讨论】:

      【解决方案2】:
      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}/>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-05
        • 2020-08-20
        • 2020-01-09
        • 1970-01-01
        • 2017-10-19
        • 2021-06-02
        • 2020-06-12
        • 2019-03-25
        相关资源
        最近更新 更多