代码之家  ›  专栏  ›  技术社区  ›  ThomasReggi

如何替换样式化组件“as”属性?

  •  0
  • ThomasReggi  · 技术社区  · 4 年前

    我正在尝试对组件进行样式化 as 属性工作,但它似乎不允许我通过这个(模拟的)自定义组件。

    import React from 'react'
    import styled, { StyledComponent } from "styled-components"
    
    export interface Props {
      as?: React.ComponentType<any> | undefined;
    }
    
    const Color = styled.div`
      color: red
    `;
    
    const PageIcon: React.ComponentType<React.HTMLProps<SVGSVGElement>> = '' as unknown as React.ComponentType<React.HTMLProps<SVGSVGElement>>
    
    function Example () {
      return <Color as={PageIcon} /> // fails here
    }
    
    const Usage = styled.div`
      ${Color} {
        background-color: black
      }
    `;
    

    我已经尝试了很多方法,能够在没有运气的情况下覆盖styled的“as”属性。

    1 回复  |  直到 4 年前
        1
  •  0
  •   ThomasReggi    4 年前

    因为styled使用它的组件来在它的css模板中使用,所以你不能仅仅交换掉维护style类型所需的类型。以下是一种方法:

    // hover over your type and copy it into it's own type
    type ColorType = StyledComponent<React.FC<Props>, any, {}, never>
    
    // then apply an intersection on the styled type and a plan react component with your custom "as"
    const Color: ColorType & React.FC<Props> = styled.div<Props>`
      color: red
    `;
    

    这是一个完整的例子,它显示了在其他情况下,如果你没有这两种情况,它是失败的 ColorType 和 React.FC<Props> .

    Typescript Playground

    推荐文章