react-dnd拖拽排序

官方文档

易懂的好文章

应用场景

 

 实现以上效果,在拖动排序上悬浮呈现可拖动状态,在其他地方悬浮无法拖动;当拖动(拖动排序时)整个组件一起被拖动。

实现拖动排序

//index.tsx

import Card from './Card.tsx'
import { DndProvider } from 'react-dnd'
import { HTML5Backend } from 'react-dnd-html5-backend'

const listData=[
   {id:1,zoneName:'区域一'},
   {id:2,zoneName:'区域二'}
]         
function dnd(){
return (   
  <DndProvider backend={HTML5Backend}>
    {
      listData.map((card, i) => (
        <Card
          key={card.id}
          index={i}
          id={card.id}
          text={card.zoneName}
          />
          ))
    }
  </DndProvider>
)
}
//Card.tsx
import { forwardRef, useImperativeHandle, useRef } from 'react';

const Card = forwardRef(function Card({ id, text, isDragging, connectDragSource, connectDropTarget, connectDragPreview }, ref) {
    const elementRef = useRef(null);
    const dragbleRef = useRef(null);
    connectDragSource(elementRef);//显示可以拖拽的(按钮)组件  
    connectDragPreview(dragbleRef)//被实际拖拽的(整体)组件
    connectDropTarget(elementRef); //被放置的组件
    useImperativeHandle(ref, () => ({
        getNode: () => elementRef.current,
    }));

     
    return (
        <div  ref={dragbleRef} >
              <span ref={elementRef} style={{cursor: 'move'}}>拖动排序</span>
              <div>{{id}}{{text}}不能显示可以拖动哦</div>
        </div>);
});

// DropTarget()(DragSource()(card))
export default DropTarget(ItemTypes.CARD, {
    hover(props, monitor, component) {
        if (!component) {
            return null;
        }
        // props:组件当前的props
        // monitor:当前拖拽状态(item,type,offsets,dropped?,,,)
        // component:当前组件实例Card(每个可拖动的元素)
        const node = component.getNode();
        if (!node) {
            return null;
        }
        const dragIndex = monitor.getItem().index;
        const hoverIndex = props.index;
        if (dragIndex === hoverIndex) {
            return;
        }
        // Card的节点边界
        const hoverBoundingRect = node.getBoundingClientRect();
        // Card高度的一半
        const hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2;
        // 鼠标的坐标
        const clientOffset = monitor.getClientOffset();
        // 鼠标距离Card的上边界距离
        const hoverClientY = clientOffset.y - hoverBoundingRect.top;
        // 往下拖动时,鼠标还没超过悬浮元素自身高度的一半就当作拖动失败
        if (dragIndex < hoverIndex && hoverClientY < hoverMiddleY) {
            return;
        }
        // 往上拖动
        if (dragIndex > hoverIndex && hoverClientY > hoverMiddleY) {
            return;
        }
        props.moveCard(dragIndex, hoverIndex);
        // 排序
        monitor.getItem().index = hoverIndex;
    },
}, (connect) => ({
    connectDropTarget: connect.dropTarget(),
}))(DragSource(ItemTypes.CARD, {
    beginDrag: (props) => ({
        id: props.id,
        index: props.index,
    }),
}, (connect, monitor) => ({
    connectDragSource: connect.dragSource(),
    connectDragPreview: connect.dragPreview(),
    isDragging: monitor.isDragging(),
}))(Card));

代码分析

☝️:DndProvider组件一定要包裹在拖动组件外侧
☝️:DropTarget()(DragSource()(Card))是js中高阶组件的写法,DropTarget,DragSource这两个函数都包括三个参数 type, spec, collect。这可以看到最后传递的参数是Card,那么 type, spec, collect这几个参数的作用显然是为了把返回值作为props传递到Card中。
☝️:从 type, spec, collect这几个参数中获取到的三个东西比较重要,分别是拖拽的按钮,被拖拽的整体以及被放入的目标组件,他们使用ref与dom进行绑定:

const elementRef = useRef(null);
    const dragbleRef = useRef(null);
    connectDragSource(elementRef);//显示可以拖拽的(按钮)组件  
    connectDragPreview(dragbleRef)//被实际拖拽的(整体)组件
    connectDropTarget(elementRef); //被放置的组件

以上代码只是实现的大概思路,可以看看文章开头的两个友情链接,很不错。

React-dnd 拖拽排序是一种常见的前端交互方式,可以通过以下代码实现:1. 首先需要安装 react-dndreact-dnd-html5-backend 两个库:``` npm install --save react-dnd react-dnd-html5-backend ```2. 在组件中引入 DragDropContext、Droppable 和 Draggable 组件:``` import { DragDropContext, Droppable, Draggable } from 'react-dnd'; import { HTML5Backend } from 'react-dnd-html5-backend'; ```3. 定义一个数组作为拖拽列表的数据源:``` const items = [ { id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }, { id: 3, name: 'Item 3' }, { id: 4, name: 'Item 4' }, { id: 5, name: 'Item 5' }, ]; ```4. 在组件中使用 DragDropContext 组件包裹整个列表,并在其中使用 Droppable 组件包裹每个拖拽项:``` <DragDropContext backend={HTML5Backend}> <Droppable droppableId="items"> {(provided) => ( <ul {...provided.droppableProps} ref={provided.innerRef}> {items.map((item, index) => ( <Draggable key={item.id} draggableId={item.id.toString()} index={index}> {(provided) => ( <li {...provided.draggableProps} {...provided.dragHandleProps} ref={provided.innerRef} > {item.name} </li> )} </Draggable> ))} {provided.placeholder} </ul> )} </Droppable> </DragDropContext> ```5. 在 Draggable 组件中使用 provided.draggableProps 和 provided.dragHandleProps 属性来实现拖拽功能,同时使用 provided.innerRef 属性来获取拖拽元素的引用。6. 在 Droppable 组件中使用 provided.droppableProps 和 provided.innerRef 属性来实现拖拽排序功能。7. 最后,需要在 DragDropContext 组件中定义 onDragEnd 回调函数来处理拖拽结束后的逻辑:``` function onDragEnd(result) { if (!result.destination) { return; } const newItems = Array.from(items); const [reorderedItem] = newItems.splice(result.source.index, 1); newItems.splice(result.destination.index, , reorderedItem); setItems(newItems); }<DragDropContext backend={HTML5Backend} onDragEnd={onDragEnd}> ... </DragDropContext> ```8. 在 onDragEnd 回调函数中,首先判断是否有目标位置,如果没有则直接返回。然后使用 Array.from 方法复制一份原始数据源,从中取出被拖拽的元素并删除,再将其插入到目标位置中,最后使用 setItems 函数更新数据源。以上就是 react-dnd 拖拽排序的代码实现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值