react拖曳組件react-dnd的簡單封裝使用

分享原因

由于項目中需要使用拖曳組件(需求:全局,跨組件,跨數(shù)據(jù)),我選擇了react-dnd

概念

React DnD 是一組 React 高階組件,我們在使用的時候只需要將目標元素進行包裹,就可以實現(xiàn)目標元素具有拖動或接受拖動的功能。它將整個拖動的事件完整的描述了出來,這使得我們在使用的過程變得簡單易用和擴展上有了無限的可能,在處理復雜拖曳和豐富需求的時候強烈建議使用它。
官網(wǎng) https://react-dnd.github.io/react-dnd/

基本

  • Item type:跟redux或其他組件一樣,item用來描述拖動dom的數(shù)據(jù)對象,type用來標識一組可拖動和接收
  • Backend:用來表現(xiàn)dom拖動現(xiàn)象,我使用了HTML5Backend
  • Monitors:用來查詢當前拖動狀態(tài)(數(shù)據(jù),dom,位置等),強大的收集功能
  • Connectors:用于Backend和組件狀態(tài)之間的連接
  • hook:useDrag 將組件作為可拖動的來源注冊到dnd useDrop 將組件作為可接收拖動來源注冊到dnd

使用方法

導入
npm install react-dnd react-dnd-html5-backend
初始化

import { HTML5Backend } from 'react-dnd-html5-backend';
 <DndProvider backend={HTML5Backend}>
     ....
 </>

組件參數(shù)type.ts

export type DragProps = {
    name: string; //名稱標記
    type: string; //暫用于標記拖拽類型,接收者和發(fā)送者一致
    role: string; //
    data: any; //綁定的數(shù)據(jù)用于拖曳后操作數(shù)據(jù)
    content: JSX.Element; //綁定的元素
    onDragFinished: Function; //拖動結束回調.
};

export type AcceptorProps = {
    name: string; //名稱標記
    type: string; //暫用于標記拖拽類型,接收者和發(fā)送者一致
    role: string; //
    data: any; //綁定的數(shù)據(jù)用于拖曳后操作數(shù)據(jù)
    content: JSX.Element; //綁定的元素
    styleType: 'background' | 'border';
    // customStyle:{
    //     canDrop:string,
    //     isActive:string
    // }
    onHover: Function; //移入?yún)^(qū)域.
};

組件MyDrag.ts

import { useDrag, useDrop } from 'react-dnd';
import { DragProps, AcceptorProps } from './type';
export const Dragger = function Dragger(option: DragProps) {
    const { name, data, type, onDragFinished } = option;
    const [{ isDragging }, drag] = useDrag(() => ({
        type: type,
        item: { name: name, data: data },
        end: (item, monitor, ...arg) => {
            console.log(arg);
            const dropResult = monitor.getDropResult();
            if (item && dropResult) {
                console.log('source:', item);
                console.log('target:', dropResult);
            }
            if (onDragFinished) {
                onDragFinished(item, dropResult);
            }
        },
        collect: (monitor) => ({
            isDragging: monitor.isDragging(),
            handlerId: monitor.getHandlerId(),
        }),
    }));
    const opacity = isDragging ? 0.4 : 1;
    return (
        <div
            ref={drag}
            role={option.role}
            style={{ opacity }}
            data-id={`${option.name}`}
        >
            {option.content}
        </div>
    );
};
export const Acceptor = (option: AcceptorProps) => {
    const { name, data, type, styleType, onHover } = option;
    const [{ canDrop, isOver }, drop] = useDrop(() => ({
        accept: type,
        drop: () => option,
        hover: () => {
            if (onHover) {
                onHover();
            }
        },
        collect: (monitor) => ({
            isOver: monitor.isOver(),
            canDrop: monitor.canDrop(),
        }),
    }));
    const isActive = canDrop && isOver;
    let backgroundColor = '#222';
    let borderBottom = '0px solid rgba(31, 92, 206, 0)';
    if (isActive) {
        backgroundColor = 'rgba(64, 224, 208, 0.3)';
        borderBottom = '1px solid #26BD11';
    } else if (canDrop) {
        backgroundColor = 'rgba(100, 149, 277, 0.3)';
        borderBottom = '1px solid #2063AF';
    }
    return (
        <div
            ref={drop}
            role={'Acceptor'}
            style={
                styleType === 'background'
                    ? { backgroundColor }
                    : { borderBottom }
            }
        >
            {option.content}
        </div>
    );
};
//同一list之間拖動
export const dragList = (
    list: Array<any>,
    crtIndex: number,
    willIndex: number,
) => {
    let targetItem = list[crtIndex];
    let delIndex = crtIndex < willIndex ? crtIndex : crtIndex + 1;
    list.splice(willIndex, 0, targetItem);
    list.splice(delIndex, 1);

    return list;
};
//來自不同list之間拖動,1.刪除原來  2不刪除原來
export const dragToList = (
    list: Array<any>,
    targetList: Array<any>,
    crtIndex: number,
    willIndex: number,
    del: 1 | 2,
) => {
    let targetItem = list[crtIndex];
    targetList.splice(willIndex, 0, targetItem);
    if (del === 1) {
        list.splice(crtIndex, 1);
    }

    return { list, targetList };
};

具體使用

import { Dragger, Acceptor, dragList } from '@/components/Drag';
//同列表之間拖曳
 handleDrag(crt: number, target: number) {
      conslog.log(dragList(newPanels, crt, target);)
    }
 renderDrag(item: ItemProps, children) {
    <Acceptor
                    key={item.type}
                    name={item.title}
                    data={item}
                    type="xxx"
                    role="xxxAccept"
                    onHover={() => {}}
                    content={
                        <Dragger
                            name={item.title}
                            data={item}
                            type="xxx"
                            role="xxxDrag"
                            content={children}
                            onDragFinished={(source: any, target: any) => {
                                console.log(source, target, '回調');
                                if (target) {
                                    this.handleDrag(
                                        source.data.sort,
                                        target.data.sort,
                                    );
                                }
                            }}
                        />
                    }
                    styleType="border"
                />
                
       }
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • 現(xiàn)在有一個新需求就是需要對一個列表,實現(xiàn)拖拽排序的功能,要實現(xiàn)的效果如下圖:? 可以通過 react-dnd 或者...
    sendSnow閱讀 13,128評論 1 2
  • 安裝yarn add react-dnd react-dnd-html5-backend 了解相應API Drag...
    Mr君閱讀 8,877評論 3 3
  • 今天與你分享的是 redux 作者 Dan 的另外一個很贊的項目 react-dnd (github 9.6k s...
    binggg_booker閱讀 36,012評論 1 13
  • 優(yōu)勢 1 .遇到一個不能忍受的問題,就是拖拽的時候那個禁止按鈕無法替換??聪逻@個拖拽組件有什么東西是別的不能替代的...
    skoll閱讀 21,738評論 0 2
  • 前言 前面文章中我寫過 react-smooth-dnd 的拖拽,它是基于 React DnD 庫實現(xiàn),將 Rea...
    arial_1df2閱讀 13,289評論 3 4

友情鏈接更多精彩內容