效果图:

React 基于Ant Degisn 实现table表格列表拖拽排序-LMLPHP

 代码:

myRow.js

import { MenuOutlined } from '@ant-design/icons';
import { DndContext } from '@dnd-kit/core';
import { restrictToVerticalAxis } from '@dnd-kit/modifiers';
import {
    arrayMove,
    SortableContext,
    useSortable,
    verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import React, { useState } from 'react';
const myRow = ({ children, ...props }) => {
    const {
        attributes,
        listeners,
        setNodeRef,
        setActivatorNodeRef,
        transform,
        transition,
        isDragging,
    } = useSortable({
        id: props['data-row-key'],
    });
    const style = {
        ...props.style,
        transform: CSS.Transform.toString(
            transform && {
                ...transform,
                scaleY: 1,
            },
        ),
        transition,
        ...(isDragging
            ? {
                position: 'relative',
                zIndex: 1,
            }
            : {}),
    };
    return (
        <tr {...props} ref={setNodeRef} style={style} {...attributes}>
            {React.Children.map(children, (child) => {
                if (child.key === 'sort') {
                    return React.cloneElement(child, {
                        children: (
                            <MenuOutlined
                                ref={setActivatorNodeRef}
                                style={{
                                    touchAction: 'none',
                                    cursor: 'move',
                                }}
                                {...listeners}
                            />
                        ),
                    });
                }
                return child;
            })}
        </tr>
    );
};

export default myRow;

index.js

import myRow from './myRow';

export default () => {
    
    const [tableDatasource, setTableDatasource] = useState([]);

    

    const tableColumns = [
        {
            key: 'sort',
            width: 20
        },
        {
            title: '印章类型名称',
            dataIndex: 'yzTypeName',
            key: 'yzTypeName',
            width: 150,
        },
        {
            title: '操作人',
            dataIndex: 'operator',
            key: 'operator',
            width: 150,
        },
        {
            title: '操作时间',
            dataIndex: 'operateDate',
            key: 'operateDate',
            width: 150,
        },
        {
            title: "操作",
            key: "action",
            width: 100,
            render: (text, record, index) => {
                return (
                    <Space size="middle">
                        <a onClick={event => {
                            tableUpdateAction(record);
                        }}>修改</a>
                        <Popconfirm
                            title="删除印章类别"
                            description="确定要删除吗?"
                            onConfirm={tableDeleteAction.bind(this, record)}
                            onCancel={tableCancelDeleteAction}
                            okText="删除"
                            cancelText="取消"
                        >
                            <a>删除</a>
                        </Popconfirm>
                    </Space>
                )
            }
        }
    ];

//注在后端返回的每个对象中,新增一个key 属性 
    useEffect(() => {
        getYzTypeList(screeningDate).then((res) => {
            if (res.code === 200) {
                const updatedList = res.data.list.map((item, index) => ({
                    ...item,
                    key: index + 1,
                }));
                setTableDatasource(updatedList);
                setMyTotal(res.data.total);
                // message.success("印章类型管理 - 数据已更新");
            }
        });
    }, [screeningDate]);
   

  
    const onDragEnd = ({active, over}) => {
        if (active.id !== over?.id) {
            setTableDatasource((previous) => {
                const activeIndex = previous.findIndex((i) => i.key === active.id);
                const overIndex = previous.findIndex((i) => i.key === over?.id);
                return arrayMove(previous, activeIndex, overIndex);
            });
            const activeId = active.id;
            const overId = over?.id;
            // 在 datasource 中找到匹配 activeId 和 overId 的项
            const activeItem = tableDatasource.find(item => item.key === activeId);
            const overItem = tableDatasource.find(item => item.key === overId);
        }
    };


    return (
        <div>
        
            <div style={{marginTop: 10}}>
                <DndContext modifiers={[restrictToVerticalAxis]} onDragEnd={onDragEnd}>
                    <SortableContext
                        items={tableDatasource.map((i) => i.key)}
                        strategy={verticalListSortingStrategy}
                    >
                <Table
                    components={{
                        body: {
                            row: myRow,
                        },
                    }}
                    rowKey="key"
                    columns={tableColumns} dataSource={tableDatasource} size={"middle"}
                       pagination={false}/>
                    </SortableContext>
                </DndContext>
            
            </div>
     
        </div>
    );
};
01-18 06:41