使用react-dnd + react-dnd-html5-backend 实现节点拖动排序

5 篇文章 0 订阅

这个是typescript类型下的自定义拖拽组件,相关api请查看官方文档

引入HTML5Backend的时候需要注意一下,目前官方文档是直接import HTML5Backend from 'react-dnd-html5-backend'; 这么导入的,但是在react-dnd-html5-backend的版本高于11之后,这么引入会报错Catched error TypeError: backendFactory is not a function, 然后去github上查看的时候,说是11版本之后,需要import { HTML5Backend } from 'react-dnd-html5-backend';这样引入才正确。

import React, { useRef } from 'react';
import { useDrop, useDrag } from 'react-dnd';
// 拖拽排序
type DragTagProps = {
    id: string;
    index: string | number;
    onDragEnd: (dragIndex: string | number, hoverIndex: string | number, type: string) => void;
    rowKey?: string;
    children?: React.ReactNode;
    type: string;
}

export const DragTag: React.FC<DragTagProps> = ({
    id = '',
    index = '',
    onDragEnd,
    children,
    rowKey = '',
    type
}) => {
    const ref = useRef(null);
    // 因为没有定义收集函数,所以返回值数组第一项不要
    const [, drop] = useDrop({
        accept: 'DragDropBox', // 只对useDrag的type的值为DragDropBox时才做出反应
        hover: (item: any) => {
            // 这里用节流可能会导致拖动排序不灵敏
            if (!ref.current) return;
            const dragIndex = item.index;
            const hoverIndex = index;
            if (dragIndex === hoverIndex) return; // 如果回到自己的坑,那就什么都不做
            onDragEnd(dragIndex, hoverIndex, type); // 调用传入的方法完成交换
            item.index = hoverIndex; // 将当前当前移动到Box的index赋值给当前拖动的box,不然会出现两个盒子疯狂抖动!
        },
        collect: monitor => ({
            isOver: monitor.isOver({ shallow: true }),
            canDrop: monitor.canDrop(),
        }),
    });

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

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

export default DragTag;

然后在外层调用

import React, { useEffect, useState } from 'react';
import { Tag } from 'antd';
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import DragTag from './DragTag';

const dataSource = [
	{ key: 23, value: 'ceshi1' },
  { key: 24, value: 'ceshi1' },
  { key: 25, value: 'ceshi1' },
  { key: 26, value: 'ceshi1' },
]

const CustomFormModal: React.FC = () => {
 const [tagData, setTagData] = useState<any[]>([]);

  const delTag = (key: CheckboxValueType, type: string) => {
  	console.log(key, type)
  };

  const onDragEnd = (dragIndex: any, hoverIndex: any, type?: string) => {
    const data = cloneDeep(dataSource);
    // 两种排序方法
    // 直接交换位置
    // const temp = data[dragIndex];
    // data[dragIndex] = data[hoverIndex];
    // data[hoverIndex] = temp;
    // 依次往后挪
    const [draggedItem] = data.splice(dragIndex, 1);
    data.splice(hoverIndex, 0, draggedItem);
    setTagData(data)
  };

  const renderTag = (data: any[], type: string) => {
    return data.map((item, index) => {
      return (
        <DragTag
          rowKey={item.key}
          index={index}
          id={item.key}
          type={type}
          key={item.key}
          onDragEnd={onDragEnd}
        >
          <Tag
            key={item.key}
          >
            {item.value}
          </Tag>
        </DragTag>
      );
    });
  };

  return (
    <DndProvider backend={HTML5Backend}>
       {renderTag(tagData, '')}
     </DndProvider>      
  );
};

export default CustomFormModal;
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
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 拖拽排序的代码实现

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值