当前位置:首页 > React

react实现拖动排序

2026-01-27 00:19:19React

实现拖动排序的基本思路

在React中实现拖动排序通常借助第三方库如react-beautiful-dndreact-dnd。这两种库提供了完整的拖放API,适合列表、看板等场景的排序需求。

使用react-beautiful-dnd

react-beautiful-dnd是Atlassian开发的拖拽库,专为列表排序优化:

安装依赖:

npm install react-beautiful-dnd

基础实现代码:

react实现拖动排序

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

基础实现代码:

react实现拖动排序

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的memouseMemo优化渲染性能。虚拟滚动库如react-window可与拖拽库配合使用。

移动端适配

移动设备需要额外处理触摸事件。react-beautiful-dnd已内置触摸支持,而react-dnd需要额外配置触摸后端。

无障碍支持

确保为拖拽元素添加适当的ARIA属性,例如:

<div
  role="button"
  aria-label="Drag handle"
  tabIndex={0}
  {...dragHandleProps}
/>

标签: 拖动react
分享给朋友:

相关文章

vue 实现拖动

vue 实现拖动

Vue 实现拖动的几种方法 在Vue中实现拖动功能可以通过多种方式,包括原生HTML5的拖放API、第三方库如vuedraggable等。以下是几种常见的实现方法: 使用HTML5拖放API HTM…

react实现vue

react实现vue

React 实现 Vue 功能 React 和 Vue 是两种不同的前端框架,但可以通过一些方法在 React 中实现 Vue 的特性。以下是几种常见 Vue 功能在 React 中的实现方式: 双…

react 如何执行

react 如何执行

安装 Node.js 和 npm React 开发需要 Node.js 环境,因为它提供了 npm(或 yarn)包管理工具。从 Node.js 官网 下载并安装最新 LTS 版本。安装完成后,在终端…

vue 实现拖动

vue 实现拖动

实现拖动的核心方法 在Vue中实现拖动功能可以通过HTML5的拖放API或第三方库如vuedraggable。以下是两种常见方案的实现细节。 使用HTML5原生拖放API HTML5提供了drag…

vue实现拖动

vue实现拖动

Vue 实现拖动的几种方法 使用 HTML5 原生拖放 API HTML5 提供了原生拖放 API,可以通过 draggable 属性、dragstart、dragend、dragover 和 dro…

vue拖动实现

vue拖动实现

Vue 拖动实现方法 在 Vue 中实现拖动功能可以通过多种方式完成,以下介绍几种常见的方法: 使用 HTML5 拖放 API HTML5 提供了原生的拖放 API,可以直接在 Vue 中使用。通…