【问题标题】:Describe to typescript react component wrapper描述到打字稿反应组件包装器
【发布时间】: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


【解决方案1】:

错误指出了问题所在:您已将 children 声明为 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'

【讨论】:

  • 嗯,你确定 vscode 控制台有空格格式吗?
  • 不,我只是在暂存缓冲区中手动完成的。在您完成前几项之后,您的眼睛可能会开始自动挑选相关位。另一件可能有帮助的事情是查看实际的 React d.ts 文件,它很大,您必须四处搜索,但至少大致了解不同的 React 类型是什么也不错。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-17
  • 2017-11-28
  • 1970-01-01
  • 2019-07-11
  • 2016-03-20
  • 2017-09-02
  • 2020-11-27
相关资源
最近更新 更多