如何描述toppy接受打字稿将正确使用的所有子项的包装器?
import Tippy, { TippyProps } from '@tippy.js/react'
import React from 'react'
import 'tippy.js/dist/tippy.css'
Tippy.defaultProps = {
maxWidth: '500px',
}
export const Tooltip: Tooltip = ({ children, content, ...rest }) => {
if (!children) return null
if (!content) return children
return (
<Tippy content={content} {...rest}>
{children}
</Tippy>
)
}
interface Tooltip {
(props: MyProps): React.ForwardRefExoticComponent<TippyProps> | null | React.ReactNode
}
interface MyProps {
content?: string | React.ReactNode
children?: React.ReactNode
}
像这样使用:
<Tooltip content='Text'>
<div>123</div>
</Tooltip>
打字稿给我孩子在return语句中的错误:
键入“字符串|编号真实| {} | ReactElement ReactElement 组件)> | null)| (新(道具:任意)=> 组件)> | ReactNodeArray | ReactPortal'不是 可分配给'ReactElement类型 ReactElement组件)> | null)| (新(道具:任意)=>组件)>'。类型'string'不能分配给类型'ReactElement ReactElement Component)> | null)| (新(道具:任意) =>组件)>'。ts(2322)index.d.ts(6,3):预期的类型来自属性'children',该属性在此声明为type 'IntrinsicAttributes&TippyProps'
答案 0 :(得分:1)
该错误将您正确地指向了问题:您已将子级声明为ReactNode,但ReactNode可以是字符串,而Tippy(显然)将不接受字符串子级。使用ReactElement代替。在调试像这样的打字稿错误时,添加空白格式通常会很有帮助(至少直到您习惯于阅读它们为止):
Type
'string | number | true | {} | ReactElement ReactElement Component)> | null)
| (new (props: any) => Component)>
| ReactNodeArray
| ReactPortal'
is not assignable to type
'ReactElement ReactElement Component)> | null)
| (new (props: any) => Component)>'
Type 'string' is not assignable to type
'ReactElement ReactElement Component)> | null)
| (new (props: any) => Component)>'
ts(2322) index.d.ts(6, 3): The expected type comes from property 'children'
which is declared here on type 'IntrinsicAttributes & TippyProps'