實現效果
首先引入react-dnd需要的npm包
import { DndProvider, DragSource, DropTarget } from 'react-dnd';
import HTML5Backend from 'react-dnd-html5-backend';
import update from 'immutability-helper';
其次設置Table中的onRow和component屬性
components={component}
onRow={ (record, index) => ({
index,
moveRow: this.moveRow,
})}
moveRow方法:
moveRow = (dragIndex, hoverIndex) => {
const { dataSource } = this.state;
const dragRow = dataSource[dragIndex];
this.setState(
update(this.state, {
dataSource: {
$splice: [[dragIndex, 1], [hoverIndex, 0, dragRow]],
},
}));
this.setState({
hasChanged: true,
});
};
引入components
import React from 'react';
import { DragSource, DropTarget } from 'react-dnd';
let dragingIndex = -1;
const BodyRow = (props) => {
const { isOver, connectDragSource, connectDropTarget, moveRow,
...restProps } = props;
const styleY = { ...restProps.style, cursor: 'move' };
let { className } = restProps;
if (isOver) {
if (restProps.index > dragingIndex) {
className += ' drop-over-downward';
}
if (restProps.index < dragingIndex) {
className += ' drop-over-upward';
}
}
return connectDragSource(
connectDropTarget(<tr {...restProps} className={className} style={styleY} />),
);
};
const rowSource = {
beginDrag(props) {
dragingIndex = props.index;
return {
index: props.index,
};
},
};
const rowTarget = {
drop(props, monitor) {
const dragIndex = monitor.getItem().index;
const hoverIndex = props.index;
if (dragIndex === hoverIndex) {
return;
}
props.moveRow(dragIndex, hoverIndex);
const mon = monitor.getItem();
mon.index = hoverIndex;
},
};
const DragableBodyRow = DropTarget('row', rowTarget, (connectIn, monitor) => ({
connectDropTarget: connectIn.dropTarget(),
isOver: monitor.isOver(),
dragingIndex,
}))(
DragSource('row', rowSource, con => ({
connectDragSource: con.dragSource(),
}))(BodyRow),
);
export const component = {
body: {
row: DragableBodyRow,
},
};