当前位置:首页 > React

react如何实现表头拖动

2026-03-31 14:54:48React

实现表头拖动的步骤

使用 react-dnd 库 安装 react-dnd 及其依赖:

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

创建可拖动的表头组件:

import { useDrag } from 'react-dnd';

const DraggableHeader = ({ id, children }) => {
  const [{ isDragging }, drag] = useDrag({
    type: 'COLUMN',
    item: { id },
    collect: (monitor) => ({
      isDragging: !!monitor.isDragging(),
    }),
  });

  return (
    <th ref={drag} style={{ opacity: isDragging ? 0.5 : 1 }}>
      {children}
    </th>
  );
};

使用 react-dnd 实现放置目标 创建可放置的表头容器组件:

react如何实现表头拖动

import { useDrop } from 'react-dnd';

const TableHeader = ({ columns, onColumnReorder }) => {
  const [, drop] = useDrop({
    accept: 'COLUMN',
    drop: (item) => onColumnReorder(item.id),
  });

  return (
    <thead ref={drop}>
      <tr>
        {columns.map((column) => (
          <DraggableHeader key={column.id} id={column.id}>
            {column.title}
          </DraggableHeader>
        ))}
      </tr>
    </thead>
  );
};

完整示例 将上述组件整合到表格中:

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

const Table = () => {
  const [columns, setColumns] = useState([
    { id: 'name', title: 'Name' },
    { id: 'age', title: 'Age' },
    { id: 'email', title: 'Email' },
  ]);

  const handleColumnReorder = (draggedId) => {
    // 实现列重新排序的逻辑
  };

  return (
    <DndProvider backend={HTML5Backend}>
      <table>
        <TableHeader columns={columns} onColumnReorder={handleColumnReorder} />
        <tbody>
          {/* 表格内容 */}
        </tbody>
      </table>
    </DndProvider>
  );
};

使用 react-beautiful-dnd 库

安装 react-beautiful-dnd

react如何实现表头拖动

npm install react-beautiful-dnd

实现可拖动表头

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

const TableHeader = ({ columns, onColumnReorder }) => {
  const handleDragEnd = (result) => {
    if (!result.destination) return;
    const newColumns = Array.from(columns);
    const [removed] = newColumns.splice(result.source.index, 1);
    newColumns.splice(result.destination.index, 0, removed);
    onColumnReorder(newColumns);
  };

  return (
    <DragDropContext onDragEnd={handleDragEnd}>
      <Droppable droppableId="columns" direction="horizontal">
        {(provided) => (
          <thead ref={provided.innerRef} {...provided.droppableProps}>
            <tr>
              {columns.map((column, index) => (
                <Draggable key={column.id} draggableId={column.id} index={index}>
                  {(provided) => (
                    <th
                      ref={provided.innerRef}
                      {...provided.draggableProps}
                      {...provided.dragHandleProps}
                    >
                      {column.title}
                    </th>
                  )}
                </Draggable>
              ))}
              {provided.placeholder}
            </tr>
          </thead>
        )}
      </Droppable>
    </DragDropContext>
  );
};

自定义实现

基本拖动逻辑 监听鼠标事件实现拖动:

const TableHeader = ({ columns, onColumnReorder }) => {
  const [draggedIndex, setDraggedIndex] = useState(null);

  const handleMouseDown = (index) => {
    setDraggedIndex(index);
  };

  const handleMouseMove = (e) => {
    if (draggedIndex === null) return;
    // 计算拖动位置并更新列顺序
  };

  const handleMouseUp = () => {
    setDraggedIndex(null);
  };

  return (
    <thead onMouseMove={handleMouseMove} onMouseUp={handleMouseUp}>
      <tr>
        {columns.map((column, index) => (
          <th
            key={column.id}
            onMouseDown={() => handleMouseDown(index)}
            style={{ cursor: 'move' }}
          >
            {column.title}
          </th>
        ))}
      </tr>
    </thead>
  );
};

样式优化 为拖动中的列添加视觉反馈:

th.dragging {
  opacity: 0.5;
  border: 2px dashed #ccc;
}

标签: 表头拖动
分享给朋友:

相关文章

vue实现表格拖动列宽

vue实现表格拖动列宽

实现表格列宽拖动的核心思路 通过监听鼠标事件(mousedown、mousemove、mouseup)实现拖拽逻辑,动态修改列宽。需要处理表头与表体的联动,确保拖动时视觉一致。 基础HTML结构 &…

vue实现数据拖动

vue实现数据拖动

Vue 实现数据拖动 使用 HTML5 拖放 API HTML5 提供了原生的拖放 API,可以通过 draggable 属性、dragstart、dragend、dragover 和 drop 事件…

jquery 拖动

jquery 拖动

jQuery 拖动实现方法 jQuery本身不直接提供拖动功能,但可以通过结合jQuery UI或原生HTML5的拖放API实现。以下是两种常见方法: 使用jQuery UI实现拖动 jQuery…

vue实现拖动效果

vue实现拖动效果

使用 vuedraggable 库实现拖动 vuedraggable 是基于 Sortable.js 的 Vue 组件库,提供简单易用的拖拽功能。安装方式如下: npm install vuedra…

vue实现鼠标拖动多选

vue实现鼠标拖动多选

Vue 实现鼠标拖动多选框 基本思路 通过监听鼠标事件(mousedown、mousemove、mouseup)实现拖动选区,结合动态计算选中元素的范围完成多选功能。核心是记录起始位置和当前鼠标位置,…

vue实现边框高度拖动

vue实现边框高度拖动

实现边框高度拖动的核心思路 通过监听鼠标事件(mousedown、mousemove、mouseup)来实现拖动效果。在Vue中结合自定义指令或组件封装更为优雅。 基础实现方案(基于自定义指令) &…