【问题标题】:How can i make an interface for a composite of styled-components?如何为样式组件的组合制作接口?
【发布时间】:2021-10-29 05:16:18
【问题描述】:

我正在尝试为样式组件的组合创建一个接口:

import styled from "styled-components"

const Title = styled.div``
const TitleNumber = styled.div``
const TitleNumberDigit = styled.div``
const TitleName: React.ComponentType = styled.div``

interface IUiStepTitleNumber extends React.ComponentType {
    Digit: React.ComponentType
}

interface IUiStepTitle extends React.ComponentType {
    Number: IUiStepTitleNumber
    Name: React.ComponentType
}

const UiStepTitle : IUiStepTitle = Object.assign(Title, {
    Number: Object.assign(TitleNumber, {
        Digit: TitleNumberDigit,
    }),
    Name: TitleName,
})

export default UiStepTitle

对于这个用例:

<UiStepTitle>
    <UiStepTitle.Number>
        <UiStepTitle.Number.Digit>
            {stepNumber}
        </UiStepTitle.Number.Digit>
    </UiStepTitle.Number>

    <UiStepTitle.Name>{stepTitle}</UiStepTitle.Name>
</UiStepTitle>

但是我的打字稿出错了

An interface can only extend an object type or intersection of object types with statically known members

如何正确组合这样的接口?

【问题讨论】:

    标签: javascript reactjs typescript styled-components


    【解决方案1】:

    最简单的解决方案是不使用组件作为命名空间。

    export const Title = styled.div``
    export const TitleNumber = styled.div``
    export const TitleNumberDigit = styled.div``
    export const TitleName: React.ComponentType = styled.div``
    

    并像使用它

    import { Title, TitleNumber, TitleNumberDigit, TitleName } from './Title' 
    
    ...
    
    
    <Title>
        <TitleNumber>
            <TitleNumberDigit>
                {stepNumber}
            </TitleNumberDigit>
        </TitleNumber>
        <TitleName>{stepTitle}</TitleName>
    </Title>
    
    

    如果您确实有一个用例,希望通过接口提供组件,您可以按如下方式构建您的接口:

    interface Title {
      Body: FC<BodyProps>;
      Number: FC<NumberProps>;
     ...
    }
    
    const fancyTitle: Title = {
      Body: FancyTitle,
      Number: FancyNumber,
     ...
    }
    
    // dummy factory
    export const createTitle = (): Title => fancyTitle;
    

    像这样使用它:

    import { createTitle } from './Title'
    
    const Title = createTitle();
    
    (
      <Title.Body>
        <Title.Number>
          ...
        </Title.Number>
        ...
      </Title.Body>
    );
    

    【讨论】:

    • 当使用多个原子组件时,我们必须使用我们想要避免的特定名称。例如``` import { BlockCommentUserTitle, BlockCommentUserRating, BlockCommentUserRatingValue, BlockCommentUserRatingValueImage } from './BlockCommentUser' import { BlockAuthorUserTitle, BlockAuthorUserRating, BlockAuthorUserRatingValue, BlockAuthorUserRatingValueImage } from './BlockAuthorUser' ```
    • 我们想要这个``` import BlockCommentUser from './BlockCommentUser' BlockCommentUser.Title BlockCommentUser.Rating BlockCommentUser.Rating.Value.Image ```
    猜你喜欢
    • 2022-11-22
    • 2021-09-19
    • 1970-01-01
    • 2021-01-25
    • 2019-11-01
    • 1970-01-01
    • 2019-11-29
    • 2021-08-16
    • 1970-01-01
    相关资源
    最近更新 更多