当前位置:首页 > 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
分享给朋友:

相关文章

react native如何启动

react native如何启动

如何启动 React Native 项目 安装 Node.js 和 npm 确保已安装 Node.js(建议版本 16 或更高)和 npm(Node.js 自带)。可通过以下命令检查版本: node…

vue 实现拖动

vue 实现拖动

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

如何react页面

如何react页面

创建 React 页面 使用 create-react-app 快速初始化项目: npx create-react-app my-app cd my-app npm start 基础页面结构 在 s…

react 如何跳转

react 如何跳转

使用 React Router 进行页面跳转 React 应用中通常使用 react-router-dom 库实现页面跳转。以下是几种常见的跳转方式: 安装依赖 npm install react…

如何构建react

如何构建react

构建 React 项目的步骤 安装 Node.js 和 npm 确保系统已安装 Node.js(包含 npm)。可通过命令行验证: node -v npm -v 使用 Create React Ap…

vue如何实现拖动

vue如何实现拖动

Vue 实现拖动的常用方法 使用 HTML5 原生拖放 API HTML5 提供了原生的拖放 API,可以通过 draggable 属性和相关事件实现拖动功能。 <template>…