antd5实体dnd-kit/sortable 实现简单table拖拽排序

DratTable/index.tsx


import type { DragEndEvent } from '@dnd-kit/core';
import { DndContext, PointerSensor, useSensor, useSensors } from '@dnd-kit/core';
import { restrictToVerticalAxis } from '@dnd-kit/modifiers';
import {
  SortableContext,
  arrayMove,
  verticalListSortingStrategy
} from '@dnd-kit/sortable';
import { Space, Table } from 'antd';
import { useState } from 'react';
import Row from './components/TableRow';

const DragTable = (props) => {
  const { searchParams } = props;
  const [data, setData] = useState<{
    id: number;
    label: string;
  }[]>([
    {
      id: 1,
      label: 'weee1',
      children: [
        {
          id: 11,
          label: 'ssw1-1'
        },
        {
          id: 12,
          label: 'ssw1-2'
        }
      ]
    },
    {
      id: 2,
      label: 'weee2'
    },
    {
      id: 3,
      label: 'weee3'
    },
    {
      id: 4,
      label: 'weee4'
    }
  ]);

  const columns: any[] = [

    {
      title:'Label',
      dataIndex: 'label',
      ellipsis: true,
     
    },
    {
      title: 'Name',
      dataIndex: 'enLabel',
      ellipsis: true,
    },
    {
      title: 'Key',
      dataIndex: 'nodeId',
      ellipsis: true,
    },

  ];
  const sensors = useSensors(
    useSensor(PointerSensor, {
      activationConstraint: {
        // https://docs.dndkit.com/api-documentation/sensors/pointer#activation-constraints
        distance: 1,
      },
    }),
  );

  const onDragEnd = ({ active, over }: DragEndEvent) => {
    console.log('active, over', active, over);

    if (active.id !== over?.id) {
      setData((prev) => {
        console.log('prev', prev);
        const activeIndex = prev.findIndex((i) => i.id === active.id);
        const overIndex = prev.findIndex((i) => i.id === over?.id);
        return arrayMove(prev, activeIndex, overIndex);
      });
    }
  };

  return (
    <DndContext sensors={sensors} modifiers={[restrictToVerticalAxis]} onDragEnd={onDragEnd}>
      <SortableContext
        items={data.map((i) => i.id)}
        strategy={verticalListSortingStrategy}
      >
        <Table
          rowKey="id"
          components={{
            body: {
              row: Row,
            },
          }}
          columns={columns}
          dataSource={data}
        />
      </SortableContext>
    </DndContext>
  );
};

export default DragTable;

DratTable/components/TableRow/index.tsx

import {
  useSortable
} from '@dnd-kit/sortable';
interface RowProps extends React.HTMLAttributes<HTMLTableRowElement> {
  'data-row-key': string;
}
const Row = (props: RowProps) => {
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging
  } = useSortable({
    id: props['data-row-key'],
  });

  const style: React.CSSProperties = {
    ...props.style,
    transform: CSS?.Transform?.toString(transform && { ...transform, scaleY: 1 }),
    transition,
    cursor: 'move',
    ...(isDragging ? { position: 'relative', zIndex: 9999 } : {}),
  };

  return <tr {...props} ref={setNodeRef} style={style} {...attributes} {...listeners} />;
};

export default Row;

在这里插入图片描述

在这里插入图片描述

DndContent组件Props

interface Props {
  announcements?: Announcements;
  autoScroll?: boolean;
  cancelDrop?: CancelDrop;
  children?: React.ReactNode;
  collisionDetection?: CollisionDetection;
  layoutMeasuring?: Partial<LayoutMeasuring>;
  modifiers?: Modifiers;
  screenReaderInstructions?: ScreenReaderInstructions;
  sensors?: SensorDescriptor<any>[];
  onDragStart?(event: DragStartEvent): void;
  onDragMove?(event: DragMoveEvent): void;
  onDragOver?(event: DragOverEvent): void;
  onDragEnd?(event: DragEndEvent): void;
  onDragCancel?(): void;
}

拖拽组件 dnd-kit

官方文档:https://docs.dndkit.com/
GitHub地址:https://github.com/clauderic/dnd-kit

@dnd-kit – 用于 React 的轻量级、模块化、高性能、可访问且可扩展的拖放工具包。

功能丰富:可定制的碰撞检测算法、多个激活器、可拖动覆盖、拖动手柄、自动滚动、约束等等。
专为 React 构建:公开诸如和 之类的钩子,并且不需要您重新构建应用程序或创建额外的包装器 DOM 节点。

支持广泛的用例:列表、网格、多个容器、嵌套上下文、可变大小的项目、虚拟化列表、2D 游戏等。
零依赖和模块化:库的核心缩小后重量约为 10kb,并且没有外部依赖。它是围绕内置的 React 状态管理和上下文构建的,这使库保持了精简。
内置支持多种输入法:指针、鼠标、触摸和键盘传感器。
完全可定制和可扩展:定制每个细节——动画、过渡、行为、样式。构建您自己的、、自定义按键绑定等等。
辅助功能:键盘支持、合理的默认咏叹调属性、可自定义的屏幕阅读器说明和内置的实时区域。
性能:它在构建时考虑了性能,以支持丝般流畅的动画。
预设:需要构建可排序的界面?检查一下,这是一个建立在上面的薄层。未来会有更多预设。@dnd-kit/core

  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值