样式化组件使用继承组件的道具接口,而不是它自己的道具接口

问题描述 投票:0回答:0

给定这些 React 组件:

Typography.tsx:

type TypographyProps = HTMLAttributes<HTMLHeadingElement> &
  PropsWithChildren & {
    id?: string
  }

const StyledTypography = styled.div`
  font-style: normal;
` 

export const Typography = (props: TypographyProps): ReactElement => (
  <StyledTypography {...props} />
)

文本.tsx:

import { Typography } from '../Typography'

type TextProps = TypographyProps & { bold?: boolean }

const Text = styled(Typography)<TextProps>`
  font-size: 16px;
  line-height: 20px;
  font-style: ${({ bold }) => (bold ? 'bold' : 'normal')};
`

当消费组件

<Text />
时,它使用道具界面
TypographyProps
而不是
TextProps
。我如何构建类型,以便
<Text />
使用
TextProps
类型作为道具?

当我使用:

<Text bold>
bold
被正确传递,但没有类型安全。例如,我也可以传递一个字符串。

reactjs typescript styled-components
© www.soinside.com 2019 - 2024. All rights reserved.