拖拽组件:react-dnd

reactreact-dnd拖拽

从昨天下午在弄一个关于拖拽的问题,实在有点心烦,先暂停下来,认真梳理一下关于这个组件的知识。


全文参考了silkshdow的文章, 原文地址 (opens in a new tab)

核心API

API参数介绍

DragSource(type, spec, collect)

DropTarget(type, spec, collect)

  1. type: 拖拽类型,必填
  2. spec: 拖拽事件的方法对象,必填。
  3. collect: 把拖拽过程中需要信息注入组件的 props,接收两个参数 connect and monitor,必填。

type

当 source组件的type 和 target组件的type 一致时,target组件可以接受source组件。

type的类型可以是 string,symbol,也可以是用一个函数来返回该组件的其他 props

spec

spec定义特定方法的对象,如 source组件的spec 可以定义 拖动 相关的事件,target组件的spec 可以定义 放置 相关的事件,具体列表:

1. DragSource specObj

// Example code here

2. DropTarget specObj

3. specObj 对象方法相关参数

4. collect

collect 是一个函数,默认有两个参数:connect 和 monitor。collect函数将返回一个对象,这个对象会注入到组件的 props 中,也就是说,我们可以通过 this.props 获取collect返回的所有属性。 传递参数时需要,项目中很多地方会需要知道当前拖拽的相关数据,很有用

5. 参数 connect

6. 参数 monitor

monitor 用于查询当前的拖拽状态,其对应实例内置了很多方法。 内置方法列表:

// Add your code here

// DragSourceMonitor monitor.canDrag() // 是否能被拖拽 monitor.isDragging() // 是否正在拖拽 monitor.getItemType() // 拖拽组件type monitor.getItem() // 当前拖拽的item monitor.getDropResult() // 查询drop结果 monitor.didDrop() // source是否已经drop在target monitor.getInitialClientOffset() // 拖拽组件初始拖拽时offset monitor.getInitialSourceClientOffset() monitor.getClientOffset() // 拖拽组件当前offset monitor.getDifferenceFromInitialOffset() // 当前拖拽offset和初始拖拽offset的差别 monitor.getSourceClientOffset()

// DropTargetMonitor monitor.canDrop() // 是否可被放置 monitor.isOver(options) // source是否在target上方 monitor.getItemType() // 拖拽组件type monitor.getItem() // 当前拖拽的item monitor.getDropResult() // 查询drop结果 monitor.didDrop() // source是否已经drop在target monitor.getInitialClientOffset() // 拖拽组件初始拖拽时offset monitor.getInitialSourceClientOffset() monitor.getClientOffset() // 拖拽组件当前offset monitor.getDifferenceFromInitialOffset() // 当前拖拽offset和初始拖拽offset的差别 monitor.getSourceClientOffset()

// Add your code here

最后

以上是一个网友的总结,我实际上是需要在antd的table组件中使用的,react-dnd与antd-table组合又有些不同,将在下一篇文章中记录。

拖拽时候的样式重写

react-dnd-text-dragpreview (opens in a new tab)

官网例子 (opens in a new tab)

官方源码 (opens in a new tab)