如何使用箭头函数为泛型目标组件创建React forwardRef?
问题
我遇到的场景和Stack Overflow相关问题类似,但需要处理本身为泛型的组件(比如React Native的FlashList或FlatList)。
目前我通过以下方式实现,但想移除代码中的any类型:
export const DragFlashList = forwardRef<FlashList<any>, DragFlashListProps<any>>((props, ref) => <DragListImpl {...props} ref={ref} />);
尝试了函数式写法,但无法正常运行:
export function DragFlashList<T> { return forwardRef<FlashList<T>, DragFlashListProps<T>>((props, ref) => <DragListImpl {...props} ref={ref} />); }
我希望用箭头函数实现,也试过泛型箭头函数的相关技巧,但由于forwardRef的构建逻辑,以下写法并非有效的TypeScript代码:
export const DragFlashList = <T,>forwardRef<FlashList<T>, DragFlashListProps<T>>((props, ref) => <DragListImpl {...props} ref={ref} />);
解决方案
箭头函数正确实现
将泛型参数声明在forwardRef接收的渲染函数上,让渲染函数成为泛型函数,即可为FlashList和DragFlashListProps传入对应的泛型T:
import React, { forwardRef, Ref } from 'react'; export const DragFlashList = forwardRef(<T,>( props: DragFlashListProps<T>, ref: Ref<FlashList<T>> ) => ( <DragListImpl {...props} ref={ref} /> ));
修复后的函数式写法
之前的函数式写法存在语法缺失,补充完整类型声明后即可正常工作:
import React, { forwardRef, Ref } from 'react'; function DragFlashListImpl<T>( props: DragFlashListProps<T>, ref: Ref<FlashList<T>> ) { return <DragListImpl {...props} ref={ref} />; } export const DragFlashList = forwardRef(DragFlashListImpl);
写法失效原因说明
你之前的箭头函数写法将泛型T放在了箭头函数与forwardRef之间,TypeScript无法正确识别泛型的作用域。将泛型参数移至forwardRef内部的渲染函数后,TypeScript能正确推断这是一个泛型组件,同时关联FlashList<T>与DragFlashListProps<T>的类型依赖关系。
内容的提问来源于stack exchange,提问作者Archimedes Trajano
相关产品推荐
相关产品推荐

