react实现拖动排序
实现拖动排序的基本思路
在React中实现拖动排序通常借助第三方库如react-beautiful-dnd或react-dnd。这两种库提供了完整的拖放API,适合列表、看板等场景的排序需求。
使用react-beautiful-dnd
react-beautiful-dnd是Atlassian开发的拖拽库,专为列表排序优化:
安装依赖:
npm install react-beautiful-dnd
基础实现代码:

import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';
function App() {
const [items, setItems] = useState([
{ id: '1', content: 'Item 1' },
{ id: '2', content: 'Item 2' },
{ id: '3', content: 'Item 3' }
]);
const handleDragEnd = (result) => {
if (!result.destination) return;
const newItems = Array.from(items);
const [reorderedItem] = newItems.splice(result.source.index, 1);
newItems.splice(result.destination.index, 0, reorderedItem);
setItems(newItems);
};
return (
<DragDropContext onDragEnd={handleDragEnd}>
<Droppable droppableId="items">
{(provided) => (
<ul {...provided.droppableProps} ref={provided.innerRef}>
{items.map((item, index) => (
<Draggable key={item.id} draggableId={item.id} index={index}>
{(provided) => (
<li
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
>
{item.content}
</li>
)}
</Draggable>
))}
{provided.placeholder}
</ul>
)}
</Droppable>
</DragDropContext>
);
}
使用react-dnd
react-dnd是更通用的拖拽库,适合复杂场景:
安装依赖:
npm install react-dnd react-dnd-html5-backend
基础实现代码:

import { useDrag, useDrop, DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
const DraggableItem = ({ id, text, index, moveItem }) => {
const [, ref] = useDrag({
type: 'ITEM',
item: { id, index }
});
const [, drop] = useDrop({
accept: 'ITEM',
hover: (draggedItem) => {
if (draggedItem.index !== index) {
moveItem(draggedItem.index, index);
draggedItem.index = index;
}
}
});
return (
<div ref={(node) => ref(drop(node))}>
{text}
</div>
);
};
function App() {
const [items, setItems] = useState([
{ id: 1, text: 'Item 1' },
{ id: 2, text: 'Item 2' },
{ id: 3, text: 'Item 3' }
]);
const moveItem = (fromIndex, toIndex) => {
const newItems = [...items];
const [movedItem] = newItems.splice(fromIndex, 1);
newItems.splice(toIndex, 0, movedItem);
setItems(newItems);
};
return (
<DndProvider backend={HTML5Backend}>
{items.map((item, index) => (
<DraggableItem
key={item.id}
id={item.id}
text={item.text}
index={index}
moveItem={moveItem}
/>
))}
</DndProvider>
);
}
性能优化建议
对于长列表场景,应结合React的memo或useMemo优化渲染性能。虚拟滚动库如react-window可与拖拽库配合使用。
移动端适配
移动设备需要额外处理触摸事件。react-beautiful-dnd已内置触摸支持,而react-dnd需要额外配置触摸后端。
无障碍支持
确保为拖拽元素添加适当的ARIA属性,例如:
<div
role="button"
aria-label="Drag handle"
tabIndex={0}
{...dragHandleProps}
/>





