首页 > 解决方案 > 带有 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) 没有共同的属性

代码本身是有效的,更改checkJsfalse解决此问题,但我们希望保留checkJs true.

我们到底做错了什么?

标签: reactjstypescriptreact-nativevisual-studio-code

解决方案


我不确定你在做什么propTypes,但你可以通过设置泛型来定义 props 和 ref 类型forwardRef

export const Box = React.forwardRef<View, {padding?: string | number}>(({ padding, children }, ref) => {
  return (
    <View ref={ref} style={{ padding }}>
      {children}
    </View>
  );
});

游乐场链接


推荐阅读