You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Typescript中DraggableFlatList的onRef属性类型错误如何修复?

修复方案

错误根因

react-native-draggable-flatlist的onRef属性预期接收的是回调函数,不是直接传入useRef创建的可变ref对象,所以会出现类型不匹配报错。

修复后代码

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

// 补充你自己的业务类型定义
interface ITask {
  id: string
  // 其他任务字段
}
type Props = {
  // 组件入参字段
}

export default function TasksList(props: Props) {
    // 函数组件统一用useRef即可,不需要createRef
    const draggableListRef = useRef<DraggableFlatList<ITask>>(null)
    const flatListRef = useRef<FlatList<ITask> | null>(null)

    // 调用scrollToIndex的示例方法
    const scrollToTargetIndex = (index: number) => {
      flatListRef.current?.scrollToIndex({
        index,
        animated: true
      })
    }

    return (
        <DraggableFlatList
            ref={draggableListRef}
            // 核心修改:用回调接收内部FlatList实例,赋值到你自己的ref
            onRef={(innerFlatListRef) => {
              flatListRef.current = innerFlatListRef
            }}
            // 其他原有属性配置...
        />
    )
}

额外说明

  • 函数组件不需要使用createRef,统一用useRef维护引用即可
  • 如果仍有类型报错,确认你导入的FlatList和DraggableFlatList内部依赖的FlatList来源一致,你当前已经从react-native-gesture-handler导入,符合组件要求
  • 后续需要调用内部FlatList方法时,直接访问flatListRef.current对应的API即可

内容的提问来源于stack exchange,提问作者checklist

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 23:06:04