import { DndProvider, useDrag, useDrop } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import update from 'immutability-helper';
const type = 'DragableBodyRow';
const DragableBodyRow = ({ index, moveRow, className, style, ...restProps }) => {
const ref = useRef();
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 => {
moveRow(item.index, index);
},
});
const [, drag] = useDrag({
type,
item: { index },
collect: monitor => ({
isDragging: monitor.isDragging(),
}),
});
drop(drag(ref));
return (
<tr
ref={ref}
className={`${className}${isOver ? dropClassName : ''}`}
style={{ cursor: 'move', ...style }}
{...restProps}
/>
);
};
方法:
//拖拽
const components = {
body: {
row: DragableBodyRow,
},
};
const moveRow = useCallback(
(dragIndex, hoverIndex) => {
console.log('dragIndex, hoverIndex',dragIndex, hoverIndex)
console.log('data',data)
// var data = data.items
console.log('data.items',data.items)
const dragRow = data.items[dragIndex];
console.log('dragRow',dragRow)
setData({
items:update(data.items, {
$splice: [
[dragIndex, 1],
[hoverIndex, 0, dragRow],
],
}),
});
},
[data],
);
用法:
<AdvancedTable
data={data}
columns={columns}
// components={components}
// onRow={(record, index) => ({
// index,
// moveRow,
// })}
></AdvancedTable>