0

我在 Stack Overflow 上看到了很多关于如何在 React 中键入正向引用的答案,虽然其中一些答案适用于我的应用程序的某些部分,但在这种情况下,它们都不起作用。

我正在使用 React Native 并返回一个由 forwardRef 包装的 View 组件。我已经设法输入了 ref 参数,但我似乎无法创建一个能让 TS 编译器满意的 props 接口。我得到的错误令我感到奇怪的是,键入 props 接口会导致在将 ref 传递给组件时引发错误,但正如我所说,ref 已经键入。这是我必须要做的:

import React, { forwardRef, ReactNode, Ref } from 'react';
import { View as RNView } from 'react-native';

export type X = unknown;
export type ViewPropsType<P> = { [key: string]: P };
export type ViewRefType = Ref<ReactNode> | ReactNode;

const View = forwardRef<ViewRefType, ViewPropsType<X>>((props, ref) => (
    <RNView ref={ref} {...props} />
));

View.displayName = 'View';

export default View;

ref={ref}当我将 props 接口从 type of 更改为上述类型时,TS 编译器会在此处突出显示一个错误any

No overload matches this call.
  Overload 1 of 2, '(props: ViewProps | Readonly<ViewProps>): View', gave the following error.
    Type 'ForwardedRef<ViewRefType>' is not assignable to type 'LegacyRef<View> | undefined'.
      Type 'MutableRefObject<ViewRefType>' is not assignable to type 'LegacyRef<View> | undefined'.
        Type 'MutableRefObject<ViewRefType>' is not assignable to type 'RefObject<View>'.
          Types of property 'current' are incompatible.
            Type 'ViewRefType' is not assignable to type 'View | null'.
              Type 'undefined' is not assignable to type 'View | null'.
  Overload 2 of 2, '(props: ViewProps, context: any): View', gave the following error.
    Type 'ForwardedRef<ViewRefType>' is not assignable to type 'LegacyRef<View> | undefined'.ts(2769)

如何在不使用任何内容的情况下键入此内容?

4

0 回答 0