reactjs - TS2739:无法在 typescript 中使用扩展 TippyProps 的自定义 Tippy 包装器
问题描述
我们维护两个独立的存储库作为库。两者都在使用 reactjs。一个是纯组件库,而另一个包含可共享的模块。
我开始在这两个库中集成打字稿。
这是在组件库中命名Tippy.tsx的Tippy 包装器。
import Tooltip, {TippyProps} from '@tippyjs/react'
interface TippyType extends TippyProps {
hook: string;
style: Object;
}
const Tippy:React.FC<TippyType> = (props) => {
const {dataHook = '', style = {}} = props
function onCreate (instance: any) {
props?.onCreate?.(instance)
if (dataHook) {
instance.props.content.setAttribute('data-hook', dataHook)
}
Object.entries(style).forEach(([property, value]) => {
content.style[property] = value
})
}
return (
<Tooltip
{ ...props}
onCreate={onCreate}
>
{props.children}
</Tooltip>
)
}
export default Tippy
此代码构建成功。但是当我尝试在模块库中使用这个组件时,打字稿只承认钩子和样式道具。来自tippy PropTypes 的所有其他道具都会抛出错误。
例如以下代码
<Tippy
content={value}
theme='material'
>
<span className='inline-block m-r-5 to-ellipsis overflow-hidden ws-nowrap'>{value}</span>
</Tippy>
投掷
TS2739:类型'{孩子:元素;内容:字符串;主题:字符串;}' 缺少类型 'TippyType' 的以下属性:hook、'style'
这里是自动生成的声明文件tippy.d.ts
import { TippyProps } from '@tippyjs/react';
import React from 'react';
import './styles.scss';
import 'tippy.js/dist/tippy.css';
interface TippyType extends TippyProps {
hook: string;
'style': Object;
}
declare const Tippy: React.FC<TippyType>;
export default Tippy;
这里是TippyProps
解决方案
TS2739:类型'{孩子:元素;内容:字符串;主题:字符串;}' 缺少类型 'TippyType' 的以下属性:hook、'style'
该错误是在警告您hook
,并且style
在 Tippy 组件中是强制性的。
interface TippyType extends TippyProps {
hook: string; // <--- compulsory
style: Object; // <--- compulsory
}
hook
因此,style
使用时需要通过Tippy
.
<Tippy
hook=""
style={{}}
content={value}
theme='material'
>
<span className='inline-block m-r-5 to-ellipsis overflow-hidden ws-nowrap'>{value}</span>
</Tippy>
如果要将 和 标记hook
为style
可选,请使用?
:
interface TippyType extends TippyProps {
hook?: string;
style?: Object;
}
推荐阅读
- python - Pyspark.sql:如何使用 python 删除空白空间并仅保留数据的特定部分
- reactjs - 错误:应该有一个队列。这可能是 React 中的一个错误。请提出问题
- django - 我已经将我的 django 应用程序推向生产,但是当我打开媒体文件时,它会引发 django.views.static.serve 错误
- javascript - 对象嵌套 Uint8Array(32) 到 String 到 btoa 到 localStorage 到 atob 到 Uint8Array(32)
- ios - 我想知道如何使用 REST API 请求 POST。(迅速)
- django - Django Rest Framework - “unique_together”内部服务器错误。如何响应错误
- java - 如何对java列表进行排序
- bootstrap-4 - 在移动视图中集中页面上的导航按钮
- rust - newterm 使用 ncurses 板条箱
- c++ - 如何同步 NMEA gps 语句的输出