【发布时间】:2020-03-22 01:15:11
【问题描述】:
如何描述tippy接受typescript将正确使用的任何孩子的包装器?
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>
Typescript 在 return 语句中给我的孩子错误:
键入'字符串 |号码 |真实 | {} |反应元素反应元素 组件)> |空) | (新(道具:任何)=> 组件)> |反应节点数组 | ReactPortal' 不是 可分配给类型'ReactElement ReactElement 组件)> |空) | (新(道具:任何)=> 组件)>'。类型 'string' 不可分配给类型 'ReactElement ReactElement 组件)> |空) | (新(道具:任何) => Component)>'.ts(2322) index.d.ts(6, 3): 预期的类型来自属性 'children',它在 type 上声明 'IntrinsicAttributes & TippyProps'
【问题讨论】:
-
错误指出你的问题是正确的:你已经声明 children 是一个 ReactNode 但 ReactNode 可以是一个字符串,并且 Tippy (显然)不会接受字符串孩子。改用 ReactElement。在调试这样的打字稿错误时,添加空格格式通常很有帮助(至少在您习惯阅读它们之前)。
-
@JaredSmith thx,你应该回答,而不是评论,所以我可以接受你的回答 :)
-
@JaredSmith thx,我真的很难阅读这个错误。不知道空格格式。
-
是的,它们非常密集。我在刚刚发布的答案中举了一个例子,我所做的只是添加了一些战略性的回车。
标签: reactjs typescript tippyjs