前言
相信大家都和我一样,都觉得antd文档中table组件拖拽排序的示例很麻烦,尤其是必须引入一堆东西。
超简单实现方案
let dragStartId = ''
const onRow = (record: any, state: any[], setState: any) => ({
draggable: true,
style: { cursor: 'move' },
onDragStart: (ev: any) => {
ev.dataTransfer.effectAllowed = 'move'
dragStartId = record.id
},
onDragEnter: (ev: any) => {
const nodes = ev.target.parentNode.childNodes
nodes.forEach((item: any) => (item.style.borderTop = '2px dashed #1890ff'))
},
onDragLeave: (ev: any) => {
const nodes = ev.target.parentNode.childNodes
nodes.forEach((item: any) => (item.style.borderTop = ''))
},
onDrop: (ev: any) => {
ev.preventDefault()
ev.stopPropagation()
const dropCol = ev.target.tagName !== 'TR' ? ev.target.parentNode : ev.target
const dropId = record.id
const dragIndex = state.findIndex((item: any) => item.id === dragStartId)
const dropIndex = state.findIndex((item: any) => item.id === dropId)
const data = [...state]
const item = data.splice(dragIndex, 1) // 移除拖动前的元素
data.splice(dropIndex, 0, item[0]) // 将拖动元素插入到新的位置
setState(data)
dropCol.childNodes.forEach((item: any) => (item.style.borderTop = ''))
},
onDragOver: (ev: any) => ev.preventDefault() })
使用
const [tableData, setTableData] = useState<any>([])
<Table
columns={columns}
dataSource={tableData}
pagination={false}
rowKey="id"
onRow={(record: any) => onRow(record, tableData, setTableData)}
/>