我想要一个简单的组件,我可以设置样式并使用 as
传递 output
元素类型的 prop。将 5
的 styled-components
和 4
用于 TS
但是我收到以下 TS 错误
No overload matches this call.
Overload 1 of 2, '(props: Omit<Omit<Pick<DetailedHTMLProps<HTMLAttributes<HTMLParagraphElement>, HTMLParagraphElement>, "key" | keyof HTMLAttributes<...>> & { ...; }, never> & Partial<...>, "theme"> & { ...; } & { ...; }): ReactElement<...>', gave the following error.
Type 'string' is not assignable to type 'undefined'.
This JSX tag's 'children' prop expects type 'never' which requires multiple children, but only a single child was provided. TS2769
11 | color: #000;
12 | `
> 13 | return <Component as={as}>{children}</P>
| ^
14 | }
15 |
这个错误的关键部分在这里我相信 Type 'string' is not assignable to type 'undefined'.
但是我的理解是对于 {as = 'p'}
这是 as
的默认值?
import React, { ReactChildren } from 'react'
import styled from 'styled-components'
export interface TextProps {
as?: string
children?: ReactChildren | React.ReactNode | string
}
export const Text = ({ as = 'p', children }: TextProps) => {
const Component = styled.p`
color: #000;
`
return <Component as={as}>{children}</Component>
}
答案 0 :(得分:1)
这个有点棘手。首先,对于 type correctly Component
接受 as
道具,您应该为该 as-component
提供正确的输入。第二个问题是 string
的宽度足以导致 never
的任何其他道具的 <Component as={as as string}>
类型。包括 children
道具。因此,必须为至少已知的 html 标签缩小 as
的类型(只要您只允许在那里传递字符串而不是自定义反应组件)。
所以你的代码可能被重写为:
import React, { ReactChildren } from 'react'
import styled from 'styled-components'
type KnownTags = keyof JSX.IntrinsicElements
export interface TextProps {
as?: KnownTags
children?: ReactChildren | React.ReactNode | string
}
export const Text = ({ as = 'p', children }: TextProps) => {
const Component = styled.p`
color: #000;
`
return <Component<typeof as> as={as}>{children}</Component>
}