DraggableFlatList onRef 使用 Typescript 获取错误类型

DraggableFlatList onRef getting a wrong type with Typescript

我在 ReactNative 中使用 react-native-draggable-flatlist。我对 FlatList 的引用感兴趣,这样我就可以对其执行 scrollToIndex。使用以下代码:

import React, {
    useEffect, createRef, useRef,
} from 'react'
import { ScrollView, FlatList } from 'react-native-gesture-handler'
import DraggableFlatList, {
    RenderItemParams, DragEndParams,
} from "react-native-draggable-flatlist"

export default function TasksList(props: Props) {

    const ref = createRef<DraggableFlatList<ITask>>()
    const flatListRef = useRef<FlatList<ITask> | null>(null)

    return (
        <DraggableFlatList
            ref={ref}
            onRef={flatListRef}
...
    )
}

我收到以下 Typescript 错误:

Type 'MutableRefObject<(ComponentClass<FlatListProps & NativeViewGestureHandlerProps & RefAttributes, any> & { ...; }) | (FunctionComponent<...> & { ...; }) | null>' is not assignable to type '(ref: RefObject<FlatList>) => void'. Type 'MutableRefObject<(ComponentClass<FlatListProps & NativeViewGestureHandlerProps & RefAttributes, any> & { ...; }) | (FunctionComponent<...> & { ...; }) | null>' provides no match for the signature '(ref: RefObject<FlatList>): void'. The expected type comes from property 'onRef' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<DraggableFlatList> & Pick<Readonly<Modify<FlatListProps, { ...; } & Partial<...>>> & Readonly<...>, "ItemSeparatorComponent" | ... 150 more ... | "children"> & Partial<...> & Partial<...>'

如何修复错误以便我可以使用 ref/onRef?

我相信您没有得到 onRef 道具期望到达这里的东西。如果您仔细查看错误,它会沿着类似这样的行显示:

'MutableRefObject<FlatList<ITask> | null>' is not 
    assignable to type '(ref: RefObject<FlatList<ITask>>) => void'.

所以,它显然需要一个函数而不是 RefObject。您也可以参考 source code 来验证:

    ...
    onRef?: (ref: React.RefObject<FlatList<T>>) => void;
    ...

它期望一个函数将被赋予 RefObject<FlatList<T>> 类型的引用。

您可以将代码重写为:

    ....
    const ref = createRef<DraggableFlatList<ITask>>()
    const flatListRef = useRef<React.RefObject<FlatList<ITask>> | null>(null)

    return (
        <DraggableFlatList
            ref={ref}
            onRef={(ref) => { flatListRef.current = ref }}

所以在 flatListRef 内通过它的引用 current 属性 你将可以访问底层 FlatList ref.