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

TypeScript中使用react-dnd的useDrag方法取不到isDragging属性如何解决

问题原因

这个报错是TypeScript无法自动推断useDrag钩子collect函数的返回值类型,默认将返回的状态对象推断为unknown类型,因此识别不到isDragging属性。

解决方案

推荐使用显式声明泛型的方式保证类型安全,操作步骤如下:

  1. 先从react-dnd导入类型定义:
import { useDrag, DragSourceMonitor } from 'react-dnd';
  1. 自定义拖拽项和collect返回结果的类型:
// 拖拽元素携带的item数据类型,属性根据你的实际业务调整
type DragImageItem = {
  type: string;
  id: number | string; // 和你业务中image.id的类型保持一致
  index: number;
};

// collect方法返回的状态类型
type DragCollectResult = {
  isDragging: boolean;
};
  1. 给useDrag钩子传入对应的泛型,同时给monitor指定类型:
const [{ isDragging }, drag] = useDrag<DragImageItem, DragCollectResult>({
  // item表示拖拽元素的类型、唯一标识id和位置索引
  item: { type, id: image.id, index },
  // collect方法类似事件监听器,用于监听元素拖拽状态并对外暴露相关信息
  collect: (monitor: DragSourceMonitor<DragImageItem>) => ({
    isDragging: monitor.isDragging()
  })
});

临时简化方案

如果只是临时调试不想定义完整类型,也可以使用类型断言快速解决,但长期使用不推荐:

const [{ isDragging }, drag] = useDrag({
  item: { type, id: image.id, index },
  collect: monitor => ({
    isDragging: monitor.isDragging()
  })
}) as [{ isDragging: boolean }, (node: HTMLElement | null) => void];

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 01:15:11