1、安装依赖
npm install react-movable antd
2、使用Demo
<DragDropSort
items={[{id: 1, name: 'hh', age: 11}, {id: 2, name: 'aa', age: 26}]}
onChange={(value) => {
console.log('拖拽后的数据:', value)
}}
render={(row) => {
return <div>测试数据id:{row.id}</div>
}}
style={{ width: 300 }}
/>
3、拖拽排序组件代码
import React, { useState } from 'react';
import { List, arrayMove } from 'react-movable';
import { Card } from 'antd';
const initialImages = [{ id: '10' }, { id: '20' }, { id: '30' }, { id: '40' }, { id: '50' }, { id: '60' }];
type IItemsType = {
id: string | number;
[key: string]: any;
};
interface IProps {
style?: React.CSSProperties;
items: IItemsType[];
onChange: (newItems: IItemsType[]) => void;
render?: (row: IItemsType) => React.ReactNode | string | number;
scroll?: { y?: number };
}
const DragDropSort = (props: IProps) => {
const { items = initialImages, onChange, render, style = {}, scroll = {} } = props;
const [dragDropCard, setDragDropCard] = useState(items);
const scrollStyle: React.CSSProperties = {
...style,
display: 'flex',
flexDirection: 'column',
height: scroll?.y || 'auto',
...(scroll?.y ? { overflowY: 'auto' } : {}),
};
return (
<List
values={dragDropCard}
onChange={({ oldIndex, newIndex }) => {
const data = arrayMove(dragDropCard, oldIndex, newIndex);
setDragDropCard(data);
onChange && onChange(data);
}}
renderList={({ children, props }) => (
<div {...props} style={{ ...scrollStyle, ...(props as any).style }}>
{children}
</div>
)}
renderItem={({ value, props }) => (
<div {...props}>
<Card hoverable>{render ? render(value) : <div>我是测试卡片内容{value.id}</div>}</Card>
</div>
)}
/>
);
};
export default DragDropSort;