当前位置:首页 > React

react原生实现拖拽排序

2026-01-27 17:41:30React

使用 react-dnd 实现拖拽排序

react-dnd 是一个流行的 React 拖拽库,基于 HTML5 拖拽 API 实现。安装依赖:

npm install react-dnd react-dnd-html5-backend

创建可拖拽项和放置区域组件:

import { useDrag, useDrop } from 'react-dnd';

const DraggableItem = ({ id, text, index, moveItem }) => {
  const [{ isDragging }, drag] = useDrag({
    type: 'ITEM',
    item: { id, index },
    collect: (monitor) => ({
      isDragging: monitor.isDragging(),
    }),
  });

  const [, drop] = useDrop({
    accept: 'ITEM',
    hover: (draggedItem) => {
      if (draggedItem.index !== index) {
        moveItem(draggedItem.index, index);
        draggedItem.index = index;
      }
    },
  });

  return (
    <div
      ref={(node) => drag(drop(node))}
      style={{
        opacity: isDragging ? 0.5 : 1,
        padding: '8px',
        margin: '4px',
        border: '1px solid #ddd',
      }}
    >
      {text}
    </div>
  );
};

实现排序容器:

import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';

const SortableList = ({ items, setItems }) => {
  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-beautiful-dnd 实现拖拽排序

react-beautiful-dnd 是专为列表排序优化的拖拽库。安装依赖:

npm install react-beautiful-dnd

实现可排序列表:

import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';

const SortableList = ({ items, setItems }) => {
  const handleDragEnd = (result) => {
    if (!result.destination) return;

    const newItems = [...items];
    const [reorderedItem] = newItems.splice(result.source.index, 1);
    newItems.splice(result.destination.index, 0, reorderedItem);
    setItems(newItems);
  };

  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}
                    style={{
                      padding: '8px',
                      margin: '4px',
                      border: '1px solid #ddd',
                      ...provided.draggableProps.style,
                    }}
                  >
                    {item.text}
                  </div>
                )}
              </Draggable>
            ))}
            {provided.placeholder}
          </div>
        )}
      </Droppable>
    </DragDropContext>
  );
};

自定义实现拖拽排序

不依赖第三方库的基础实现:

const SortableList = ({ items, setItems }) => {
  const [draggedItem, setDraggedItem] = useState(null);

  const handleDragStart = (index) => {
    setDraggedItem(index);
  };

  const handleDragOver = (index) => {
    if (draggedItem === null || draggedItem === index) return;

    const newItems = [...items];
    const [movedItem] = newItems.splice(draggedItem, 1);
    newItems.splice(index, 0, movedItem);
    setItems(newItems);
    setDraggedItem(index);
  };

  return (
    <div>
      {items.map((item, index) => (
        <div
          key={item.id}
          draggable
          onDragStart={() => handleDragStart(index)}
          onDragOver={() => handleDragOver(index)}
          style={{
            padding: '8px',
            margin: '4px',
            border: '1px solid #ddd',
            cursor: 'move',
          }}
        >
          {item.text}
        </div>
      ))}
    </div>
  );
};

性能优化建议

对于大型列表,应优化渲染性能:

  • 为列表项添加稳定的 key
  • 使用 React.memo 包装列表项组件
  • 避免在拖动过程中不必要的重新渲染
  • 考虑虚拟滚动技术处理超长列表

移动端适配注意事项:

react原生实现拖拽排序

  • 添加 touch 事件处理
  • 调整拖拽灵敏度
  • 考虑使用 react-dnd-touch-backend 作为后端

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

相关文章

react如何鉴定

react如何鉴定

React 鉴权方法 基于路由的鉴权 在 React 中,可以通过封装路由组件实现鉴权。使用 react-router-dom 检查用户是否登录,未登录则跳转至登录页。 import { Rou…

vue 实现卡片拖拽

vue 实现卡片拖拽

Vue 实现卡片拖拽 使用 HTML5 原生拖拽 API HTML5 提供了原生的拖拽 API,可以通过 draggable 属性、dragstart、dragend、dragover 和 drop…

如何配置react

如何配置react

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

react如何打包

react如何打包

打包 React 项目的基本步骤 React 项目通常使用 create-react-app 或类似的脚手架工具创建,这些工具内置了打包功能。以下是打包 React 项目的详细方法: 安装依赖并构建…

java如何react

java如何react

在Java中使用React 要在Java项目中集成React,通常需要将React前端与Java后端结合使用。以下是几种常见的方法: 使用Spring Boot作为后端 Spring Boot是一个…

react如何获取光标

react如何获取光标

获取光标位置的方法 在React中获取光标位置通常涉及处理输入框或文本区域的onChange或onSelect事件。以下是几种常见的方法: 通过selectionStart和selectionEnd…