react实现表格拖拽
React 表格拖拽实现方法
使用 React 实现表格拖拽功能可以通过原生 HTML5 拖拽 API 或第三方库(如 react-beautiful-dnd)完成。以下是两种主流方案的实现细节:
原生 HTML5 拖拽 API
-
设置可拖拽元素
-
为表格行(
<tr>)或单元格添加draggable="true"属性。 -
监听
onDragStart事件存储被拖拽数据:const handleDragStart = (e, index) => { e.dataTransfer.setData('text/plain', index); }; <tr draggable onDragStart={(e) => handleDragStart(e, rowIndex)}> {/* 单元格内容 */} </tr>
-
-
处理放置目标
-
监听
onDragOver阻止默认行为以允许放置:const handleDragOver = (e) => { e.preventDefault(); }; <tbody onDragOver={handleDragOver}> {/* 表格行 */} </tbody> -
通过
onDrop更新数据顺序:const handleDrop = (e, targetIndex) => { e.preventDefault(); const sourceIndex = e.dataTransfer.getData('text/plain'); // 更新数据数组逻辑 const newData = [...data]; const [movedItem] = newData.splice(sourceIndex, 1); newData.splice(targetIndex, 0, movedItem); setData(newData); }; <tr onDrop={(e) => handleDrop(e, targetIndex)}> {/* 单元格内容 */} </tr>
-
使用 react-beautiful-dnd 库
-
安装依赖
npm install react-beautiful-dnd -
包裹拖拽区域
-
使用
DragDropContext包裹整个表格:import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd'; <DragDropContext onDragEnd={handleDragEnd}> <table> <Droppable droppableId="tableBody"> {(provided) => ( <tbody ref={provided.innerRef} {...provided.droppableProps}> {data.map((item, index) => ( <Draggable key={item.id} draggableId={item.id} index={index}> {(provided) => ( <tr ref={provided.innerRef} {...provided.draggableProps} {...provided.dragHandleProps} > {/* 单元格内容 */} </tr> )} </Draggable> ))} {provided.placeholder} </tbody> )} </Droppable> </table> </DragDropContext>
-
-
处理拖拽结果

const handleDragEnd = (result) => { if (!result.destination) return; const newData = [...data]; const [movedItem] = newData.splice(result.source.index, 1); newData.splice(result.destination.index, 0, movedItem); setData(newData); };
样式优化建议
- 为拖拽元素添加视觉反馈(如阴影、高亮边框):
.dragging { opacity: 0.5; background-color: #f0f0f0; } - 通过
onDragStart动态添加类名:const handleDragStart = (e) => { e.target.classList.add('dragging'); }; const handleDragEnd = (e) => { e.target.classList.remove('dragging'); };
注意事项
- 性能优化:大数据量时使用虚拟滚动(如
react-window)避免渲染卡顿。 - 移动端兼容性:部分触摸设备可能需要额外库(如
react-dnd-touch-backend)。 - 数据持久化:拖拽后及时同步到后端或本地存储。






