1.先安装依赖
github地址:react-dnd
npm i react-dnd
npm i react-dnd-html5-backend
2.创建 DndProvider 组件
import { HTML5Backend } from 'react-dnd-html5-backend'
import { DndProvider } from 'react-dnd'
export default class YourApp {
render() {
return (
<DndProvider backend={HTML5Backend}>
/* 你的拖动和放置组件/应用 */
</DndProvider>
)
}
}
3.创建放置组件
使用useDrag、useDrop
import React from 'react';
import { useDrag, useDrop } from 'react-dnd';
import { message } from 'antd';
import { cloneDeep } from 'lodash';
interface IProps {
index: any
item: any
changeSelectItem: any
selectItem: any
}
export default React.memo(function DragableItem({ index, item, changeSelectItem, selectItem }: IProps) {
const moveItem = (dragIndex, dropIndex) => {
let cloneSelectItem = cloneDeep(selectItem);
if (dragIndex > dropIndex) {
cloneSelectItem.splice(dragIndex, 1); // 删除移动的
cloneSelectItem.splice(dropIndex, 0, selectItem[dragIndex]); // 插入
} else {
cloneSelectItem.splice(dropIndex + 1, 0, selectItem[dragIndex]); // 插入
cloneSelectItem.splice(dragIndex, 1); // 删除移动的
}
if (changeSelectItem) {
changeSelectItem(cloneSelectItem);
}
};
const type = 'dragableItem';
const ref = React.useRef(null);
const [{ isOver, dropClassName }, drop] = useDrop({
accept: type,
collect: monitor => {
const { index: dragIndex } = monitor.getItem() || {};
if (dragIndex === index) {
return {};
}
return {
isOver: monitor.isOver(),
dropClassName: dragIndex < index ? ' drop-over-downward' : ' drop-over-upward',
};
},
drop: (item: any) => {
moveItem(item.index, index);
},
});
const [, drag] = useDrag({
item: { ...item, type, index,id: item.key },
collect: monitor => ({
isDragging: monitor.isDragging(),
}),
});
drop(drag(ref));
return (
<span ref={ref} title={item.title}>{item.title}</span>
);
});