当前位置:首页 > 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 的优势 跨平台开发效率高 React Native 允许开发者使用 JavaScript 和 React 编写代码,同时生成 iOS 和 Android 应用,大幅减少开发成…

react如何销毁

react如何销毁

React 组件销毁的机制 在 React 中,组件的销毁通常由 React 的生命周期管理。当组件从 DOM 中移除时,React 会自动触发销毁相关的生命周期方法。以下是关键点: 组件的销毁通常…

如何下载react

如何下载react

下载 React 的方法 通过 npm 或 yarn 安装 React 可以通过包管理器 npm 或 yarn 安装。确保已安装 Node.js(包含 npm),然后在项目目录中运行以下命令:…

如何开发react

如何开发react

开发React应用的基本步骤 安装Node.js和npm 确保系统中已安装Node.js(包含npm)。可通过官网下载安装包,安装后验证版本: node -v npm -v 创建React项目…

如何配置react

如何配置react

配置React项目的步骤 安装Node.js和npm 确保系统已安装Node.js(包含npm)。可通过官网下载并安装最新版本。安装完成后,运行以下命令验证版本: node -v npm -v 创建…

react如何折叠

react如何折叠

在 React 中实现折叠功能 使用 useState 管理折叠状态 通过 useState 定义一个状态变量来控制折叠面板的显示与隐藏。例如: const [isCollapsed, setIsC…