使用ForwardRef时如何在TypeScript中转换Flow的AbstractComponent
核心对应关系
Flow 中的 React.AbstractComponent<P, R> 用于描述接收 P 类型 props、暴露 R 类型 ref 的组件,在 TypeScript 中针对 forwardRef 实现的组件,等价类型为 React.ForwardRefExoticComponent<React.PropsWithoutRef<P> & React.RefAttributes<R>>。
代码改写方案
实际开发中 TypeScript 的 forwardRef 已经内置了完善的类型推导,绝大多数场景不需要手动标注组件变量的类型,只需要给 forwardRef 传入正确的泛型参数即可,改写后的示例代码如下:
import React, { forwardRef, useRef, useImperativeHandle } from 'react'; // 你的组件Props类型定义 type Props = { // 此处填写组件props的具体类型定义 }; const ComponentWithRef = forwardRef<HTMLInputElement, Props>( function Component(props: Props, ref): React.ReactNode { // 给useRef显式指定和ref类型对齐的泛型 const innerRef = useRef<HTMLInputElement>(null); useImperativeHandle(ref, () => innerRef.current as HTMLInputElement); return <div>MyComponent</div>; } );
如果你需要和原 Flow 代码一样显式标注组件变量的类型,可以参考下面的写法:
const ComponentWithRef: React.ForwardRefExoticComponent< React.PropsWithoutRef<Props> & React.RefAttributes<HTMLInputElement> > = forwardRef<HTMLInputElement, Props>( function Component(props: Props, ref): React.ReactNode { const innerRef = useRef<HTMLInputElement>(null); useImperativeHandle(ref, () => innerRef.current as HTMLInputElement); return <div>MyComponent</div>; } );
注意事项
- Flow 中的
Node类型对应 TypeScript 中的React.ReactNode类型。 - 如果你只是简单转发 ref 到内部 DOM 元素,不需要自定义暴露的 ref 方法,可以省略
useImperativeHandle,直接把 ref 挂载到对应 DOM 元素上即可。 - 如果遇到 ref 类型不兼容的提示,可以通过类型断言或者调整
useRef泛型的联合类型(比如useRef<HTMLInputElement | null>(null))解决。
内容的提问来源于stack exchange,提问作者Batman
相关产品推荐
相关产品推荐

