React Native中forwardRef组件如何正确定义无any的props泛型接口
问题原因
- Ref类型定义错误:你定义的
ViewRefType不符合React Native原生View组件的ref预期类型,原生View的ref只能指向自身实例或null,你声明的Ref<ReactNode> | ReactNode包含了大量不兼容的类型,导致赋值时报错。 - Props类型定义不规范:你自定义的
ViewPropsType没有继承RN内置的ViewProps,既会导致原生View属性没有类型提示,也会加剧类型匹配异常。
修正方案
以下是完全无any的正确类型定义代码:
import React, { forwardRef, ElementRef } from 'react'; import { View as RNView, ViewProps } from 'react-native'; // 如需扩展自定义props,可按下方注释方式合并 // export type ViewPropsType = ViewProps & { // customProp?: string; // }; export type ViewPropsType = ViewProps; // 自动推导RN View的实例类型作为ref类型,避免手动声明的类型错配问题 export type ViewRefType = ElementRef<typeof RNView>; const View = forwardRef<ViewRefType, ViewPropsType>((props, ref) => ( <RNView ref={ref} {...props} /> )); View.displayName = 'View'; export default View;
补充说明
如果你的封装需要支持额外自定义属性,只需要在ViewPropsType中扩展对应的类型定义即可,所有原生View属性的类型会自动继承,TS不会再抛出类型错误。
内容的提问来源于stack exchange,提问作者Mr. Robot
相关产品推荐
相关产品推荐

