react-dnd实现列表拖拽排序


前言

项目原本使用了react-beautiful-dnd来实现拖拽效果,由于项目中在最外层的layout布局中会根据屏幕的宽度和设置的适配宽度比较计算来得出 transform: 'scale属性的值来做不同分辨率下的屏幕的兼容和适配;奈何 react-beautiful-dnd是根据 DOM 元素的位置和尺寸来计算的。当改变元素的缩放比例时,会改变元素的位置和尺寸,会导致拖拽操作的计算不准确,从而导致拖拽异常拖拽的元素跑偏.于是直接改用react-dnd,解决问题


一、React-dnd是什么

React dnd 是一组 React 高阶组件,使用的时候只需要使用对应的 API 将目标组件进行包裹,即可实现拖动或接受拖动元素的功能。将拖动的事件转换成对象中对应状态的形式,不需要开发者自己判断拖动状态,只需要在传入的 spec 对象中各个状态属性中做对应处理即可。

二、安装

npm i react-dnd react-dnd-html5-backend

三、代码使用

1.首先在最外层导入

我是在 Layout 文件导入

// 最外层的 Layout 文件
//导入
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';


return <DndProvider backend={HTML5Backend}>
          {children}
       </DndProvider>

2.组件封装

react-dnd 封装方便之后进行使用

import React, { useRef } from 'react';
import { useDrag, useDrop } from 'react-dnd';
// dnd拖拽排序
export default ({ children, index = '', changePosition = () => {}, ...props }) => {
  const dragRef = useRef(null);

  // 因为没有定义收集函数,所以返回值数组第一项不要
  const [, drop] = useDrop({
    accept: 'DragDropBox', // 只对useDrag的type的值为DragDropBox时才做出反应
    hover: (item, monitor) => {
      if (!dragRef.current) return;
      const dragIndex = item.index;
      const hoverIndex = index;
      if (dragIndex === hoverIndex) return; // 如果回到自己的坑,那就什么都不做
      changePosition(dragIndex, hoverIndex); // 调用传入的方法完成交换
      item.index = hoverIndex; // 将当前当前移动到Box的index赋值给当前拖动的box,不然会出现两个盒子疯狂抖动!
    },
  });

  const [{ isDragging }, drag] = useDrag(() => ({
    type: 'DragDropBox',
    item: { type: 'DragDropBox', index },
    collect: monitor => ({
      isDragging: monitor.isDragging(), // css样式需要
    }),
  }));

  return (
    // ref 这样处理可以使得这个组件既可以被拖动也可以接受拖动
    <div ref={drag(drop(dragRef))} style={{ opacity: isDragging ? 0.5 : 1 }}>
      <div {...props}>{children}</div>
    </div>
  );
};

3.页面中使用

import { cloneDeep } from 'lodash';
import React, { useState } from 'react';
import DndDrag from '@/component/DndDrag';
/***
* segment:要循环的列表数组
* onChange:把修改的数据传出,之后方便处理
*/
export default ({ segment = [], onChange }) => {
  if (segment.length === 0) {
    return null;
  }
  const [dataSource, setDataSource] = useState(segment);

  // ***********************************************************逻辑方法

  const changePosition = (dragIndex, hoverIndex) => {
    let data = cloneDeep(dataSource);
    //这里将拖拽的数据修改位置
    const temp = data[dragIndex];
    data[dragIndex] = data[hoverIndex];
    data[hoverIndex] = temp;
    //重新放入循环列表中
    // 注意这代码执行过于频繁不适宜传出数据
    setDataSource(data);
  };

  // ***********************************************************渲染页面

  return (
    <>
      {dataSource.map((item, index) => {
        return (
          <DndDrag key={item.id} index={index} changePosition={changePosition}>
            <div
              draggable="true"
              onDragEnd={() => {
                onChange && onChange(dataSource);
                // 通过 div 身上 onDragEnd 事件来判断拖拽结束将数据传出
              }}
            >
              //这里写列表遍历内容
            </div>
          </DndDrag>
        );
      })}
    </>
  );
};

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
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、付费专栏及课程。

余额充值