react dnd 拖拽antd table

1、封裝拖拽Table

import React, { useState, useCallback, useRef, useEffect } from 'react'

import { DndProvider, useDrag, useDrop } from 'react-dnd'

import HTML5Backend from 'react-dnd-html5-backend'

import { Table } from "antd"

import update from 'immutability-helper'

 

const ItemTypes = {

ROW: 'row',

}

 

function DragTable(props) {

 

const { dataSource, columns, onChange, ...tableProps } = props;

 

const [list, setList] = useState([])

 

useEffect(() => {

setList(dataSource)

}, [dataSource])

 

const handleDrag = useCallback(

(dragIndex, hoverIndex) => {

const dragItem = list[dragIndex]

const newList = update(list, {

$splice: [

[dragIndex, 1],

[hoverIndex, 0, dragItem],

],

})

setList(newList);

onChange(newList);

},

[list],

)

 

const DraggableRow = (props) => {

 

const { index, record, handleDrag, ...restProps } = props;

 

const ref = useRef(null)

 

// 接收

const [{ isOver, canDrop }, drop] = useDrop({

accept: ItemTypes.ROW,

drop: (col) => handleDrag(col.index, index),

collect: (monitor) => ({

isOver: monitor.isOver(),

canDrop: monitor.canDrop(),

}),

})

 

const rowStyle = { ...restProps.style }

if (isOver && canDrop) {

rowStyle.background = 'green'

}

 

// 拖拽

const [{ isDragging }, drag] = useDrag({

item: { type: ItemTypes.ROW, record, index },

collect: monitor => ({

isDragging: monitor.isDragging(),

}),

})

const opacity = isDragging ? 0 : 1

 

drag(drop(ref))

return (

<tr ref={ref} {...restProps} style={{ ...rowStyle, opacity }}></tr>

)

};

 

const components = {

body: {

row: DraggableRow,

},

};

 

return (

<DndProvider backend={HTML5Backend}>

<Table

{...tableProps}

components={components}

dataSource={list}

columns={columns}

onRow={(record, index) => ({

record,

index,

handleDrag

})}

/>

</DndProvider>

)

}

export default DragTable

 

2、使用組件

 

import React from 'react'

import DragTable from "./DragTable"

 

function DragDemo(props) {

const list = [

{ id: 1, text: 'Write a cool JS library', },

{ id: 2, text: 'Make it generic enough', },

{ id: 3, text: 'Write README', },

{ id: 4, text: 'Create some examples', },

{ id: 5, text: 'note that this element is taller than the others', },

{ id: 6, text: '???', },

{ id: 7, text: 'PROFIT', },

]

const columns = [

{

title: "ID",

dataIndex: 'id',

key: 'id',

},

{

title: "text",

dataIndex: 'text',

key: 'text',

}

]

 

function handleTableDrag(list) {

console.log(list)

}

 

return <DragTable

rowKey="id"

dataSource={list}

columns={columns}

pagination={false}

onChange={handleTableDrag} />

}

export default DragDemo

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章