当前位置:首页 > React

react怎么实现拖拽排序

2026-01-27 13:03:12React

实现拖拽排序的基本思路

在React中实现拖拽排序通常需要借助第三方库,如react-dndreact-beautiful-dnd。核心逻辑是通过监听拖拽事件,动态更新数据顺序,并触发重新渲染。

使用react-dnd实现

安装依赖库:

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

创建可拖拽的列表项组件:

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

const Item = ({ 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 #ccc',
      }}
    >
      {text}
    </div>
  );
};

创建列表容器组件:

react怎么实现拖拽排序

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

const List = () => {
  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}>
      <div>
        {items.map((item, index) => (
          <Item
            key={item.id}
            id={item.id}
            text={item.text}
            index={index}
            moveItem={moveItem}
          />
        ))}
      </div>
    </DndProvider>
  );
};

使用react-beautiful-dnd实现

安装依赖库:

npm install react-beautiful-dnd

创建可排序列表:

react怎么实现拖拽排序

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

const List = () => {
  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) => (
          <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 #ccc',
                      ...provided.draggableProps.style,
                    }}
                  >
                    {item.content}
                  </div>
                )}
              </Draggable>
            ))}
            {provided.placeholder}
          </div>
        )}
      </Droppable>
    </DragDropContext>
  );
};

性能优化建议

对于大型列表,使用react-windowreact-virtualized进行虚拟滚动。在拖拽过程中避免不必要的重新渲染,可以使用React.memo优化子组件。

移动端兼容性

react-beautiful-dnd默认不支持移动端触摸事件,需要额外配置。react-dnd通过react-dnd-touch-backend可以支持触摸事件:

npm install react-dnd-touch-backend

使用时替换backend:

import { TouchBackend } from 'react-dnd-touch-backend';

// 在组件中
<DndProvider backend={TouchBackend} options={{ enableMouseEvents: true }}>
  {/* 你的组件 */}
</DndProvider>

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

相关文章

react性能如何

react性能如何

React 性能特点 React 通过虚拟 DOM(Virtual DOM)和高效的 diff 算法优化性能。虚拟 DOM 减少了直接操作真实 DOM 的开销,仅在必要时更新变化的部分。React 的…

react如何衰减

react如何衰减

React 中的动画衰减效果实现 在 React 中实现衰减效果(如滚动衰减、拖动释放后的惯性滑动)通常需要结合物理动画原理或第三方动画库。以下是几种常见方法: 使用 CSS 动画和 @keyfra…

react 如何跳转

react 如何跳转

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

react如何分

react如何分

React 分页实现方法 在 React 中实现分页功能可以通过多种方式完成,以下是几种常见的方法: 使用状态管理分页数据 在组件内部维护当前页码和每页数据量的状态,通过计算切片数据实现分页。…

react 如何循环

react 如何循环

循环渲染列表 在React中,循环渲染列表通常使用map方法。map可以遍历数组并返回一个新的React元素数组。 const items = ['Apple', 'Banana', 'Orange…

vue实现拖拽div

vue实现拖拽div

实现拖拽功能的基本思路 在Vue中实现拖拽功能可以通过HTML5的拖拽API或第三方库如vuedraggable来完成。以下是两种常见方法的详细说明: 使用HTML5拖拽API HTML5提供了原生…