React实现拖拽功能
使用 React DnD 实现拖拽
React DnD 是一个流行的拖拽库,适合复杂场景。安装依赖:
npm install react-dnd react-dnd-html5-backend
创建可拖拽组件:
import { useDrag } from 'react-dnd';
function DraggableItem({ id, text }) {
const [{ isDragging }, drag] = useDrag(() => ({
type: 'ITEM',
item: { id },
collect: (monitor) => ({
isDragging: !!monitor.isDragging(),
}),
}));
return (
<div ref={drag} style={{ opacity: isDragging ? 0.5 : 1 }}>
{text}
</div>
);
}
创建放置目标:

import { useDrop } from 'react-dnd';
function DropTarget({ onDrop }) {
const [{ canDrop, isOver }, drop] = useDrop(() => ({
accept: 'ITEM',
drop: (item) => onDrop(item.id),
collect: (monitor) => ({
isOver: !!monitor.isOver(),
canDrop: !!monitor.canDrop(),
}),
}));
return (
<div ref={drop} style={{ background: isOver ? 'lightgreen' : 'white' }}>
Drop here
</div>
);
}
使用原生 HTML5 拖拽 API
简单场景可用原生 API 实现。拖拽元素设置:
function Draggable() {
const handleDragStart = (e) => {
e.dataTransfer.setData('text/plain', 'drag-data');
};
return (
<div draggable onDragStart={handleDragStart}>
Drag me
</div>
);
}
放置区域处理:

function DropZone() {
const handleDrop = (e) => {
e.preventDefault();
const data = e.dataTransfer.getData('text/plain');
console.log('Dropped:', data);
};
return (
<div
onDrop={handleDrop}
onDragOver={(e) => e.preventDefault()}
>
Drop here
</div>
);
}
使用 react-beautiful-dnd 实现列表排序
适用于列表重排序场景。安装库:
npm install react-beautiful-dnd
实现可排序列表:
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';
function SortableList({ items, onReorder }) {
const handleDragEnd = (result) => {
if (!result.destination) return;
onReorder(result.source.index, result.destination.index);
};
return (
<DragDropContext onDragEnd={handleDragEnd}>
<Droppable droppableId="list">
{(provided) => (
<div {...provided.droppableProps} ref={provided.innerRef}>
{items.map((item, index) => (
<Draggable key={item.id} draggableId={item.id} index={index}>
{(provided) => (
<div
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
>
{item.content}
</div>
)}
</Draggable>
))}
{provided.placeholder}
</div>
)}
</Droppable>
</DragDropContext>
);
}






