我想要一个简单的组件,我可以用as
来样式和传递一个支柱--as
元素类型。使用5
of styled-components
和4
for TS
但是,我得到以下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>
}
发布于 2021-06-14 05:49:20
这个有点棘手。首先,要让正确类型 Component
接受as
支持,您应该为该as-component
提供正确的输入。第二个问题是string
足够宽,以致于任何其他<Component as={as as string}>
支持都会产生never
类型。包括children
道具。因此,必须缩小至少已知html标记的as
类型(一旦允许只在那里传递字符串,而不是自定义的react组件)。
因此,您的代码可以重写为:
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>
}
https://stackoverflow.com/questions/67970513
复制