reactjs - 带有 React.forwardRef 功能组件的 VSCode TS 错误
问题描述
我们正在使用 JavaScript(不是 TypeScript)来编写我们的组件库,并且我们checkJs: true
在项目的jsconfig.json
文件中有。
我们所有的组件都是功能组件(没有类组件)。当组件需要 ref 时,我们使用React.forwardRef
.
为了这个问题,一个组件的例子;不是一个实际的组件,而是展示了我们如何编写我们的组件:
import React from 'react';
import { View } from 'react-native';
import propTypes from './propTypes';
export const Box = React.forwardRef(({ padding, children }, ref) => {
return (
<View ref={ref} style={{ padding }}>
{children}
</View>
);
});
Box.propTypes = propTypes;
padding
但是,这会导致道具下出现这个“红色波浪线”错误:
类型 '{ children?: ReactNode; 上不存在属性 'padding' }'.ts(2339)
以及propTypes
分配的位置:
类型'{填充:必需;}' 与类型 'WeakValidationMap<RefAttributes>'.ts(2559) 没有共同的属性
并且在实现这个<Box>
组件的时候,在组件的名字下面出现了红色的波浪线,报错是:
类型'{孩子:元素;}' 与类型 'IntrinsicAttributes & RefAttributes'.ts(2559) 没有共同的属性
代码本身是有效的,更改checkJs
为false
解决此问题,但我们希望保留checkJs
true
.
我们到底做错了什么?
解决方案
我不确定你在做什么propTypes
,但你可以通过设置泛型来定义 props 和 ref 类型forwardRef
:
export const Box = React.forwardRef<View, {padding?: string | number}>(({ padding, children }, ref) => {
return (
<View ref={ref} style={{ padding }}>
{children}
</View>
);
});
推荐阅读
- postgresql - PostgreSQL | 剩余的连接槽保留给非复制超级用户连接
- python - Python:计算列表列表中的整体元素
- tfs - 通过克隆 VM 测试 TFS 升级?
- amazon-s3 - 如何将数字海洋空间中的所有文件夹文件权限私有更改为公共?
- c# - 如何在没有麦克风的情况下录制静音
- python - 无法获得带有诅咒的钥匙
- ios - GMSMapView - 模仿谷歌地图应用程序的相机动画
- date - 如何在 Hyperledger Fabric 中获取动态日期时间?
- c# - 未找到范围 (scp) 中的 Azure AD 访问令牌
- hyperledger-fabric - 运行 composer-rest-server 命令后,composer 中出现“Cannot GET /explorer”错误