react-beautiful-dnd使用问题:如何获取拖拽调整后的列顺序数据
react-beautiful-dnd 拖拽后获取列排序数组实现方法
- 首先在组件顶层维护列顺序的状态,用
useState初始化你的原始列配置,数组元素可以是列id字符串或者带唯一标识的列配置对象:
import { useState } from 'react' // 示例:初始列顺序,可替换为你自己的列配置 const [columnOrder, setColumnOrder] = useState(['name', 'age', 'address', 'operation'])
- 给外层的
DragDropContext组件绑定onDragEnd事件回调,这是拖拽结束后唯一能获取完整拖拽信息的入口:
<DragDropContext onDragEnd={handleDragEnd}> {/* 原有的表格、Droppable、Draggable组件内容不需要改动 */} </DragDropContext>
- 实现
handleDragEnd回调函数,在函数内处理拖拽结果,生成新的排序数组:
const handleDragEnd = (result) => { // 拖拽到无效区域时直接终止逻辑 if (!result.destination) return const { source, destination } = result // 拷贝原数组防止直接修改状态 const newOrder = Array.from(columnOrder) // 取出拖拽的列项 const [movedColumn] = newOrder.splice(source.index, 1) // 插入到目标位置 newOrder.splice(destination.index, 0, movedColumn) // 更新状态,此时newOrder就是拖拽后的列排序结果 setColumnOrder(newOrder) // 你可以直接在这使用排序后的数组,比如提交到后端或者做其他逻辑 console.log('最新列排序:', newOrder) }
注意:你需要保证每个Draggable组件的
draggableId和列数组内的唯一标识一一对应,index属性和列数组的下标完全匹配,最终生成的排序数组才会和实际拖拽后的显示顺序一致。
内容的提问来源于stack exchange,提问作者Marek Kamiński
相关产品推荐
相关产品推荐

