在React中创建可拖拽表格的常见方法是使用第三方库,如react-beautiful-dnd或react-dnd。
其中,react-beautiful-dnd是一个基于著名的drag-and-drop库(Draggable与Dropeable)的高级封装库。它提供了许多属性和事件以支持拖放操作,并且易于集成到React
应用
程序中。
以下是一个简单的示例,演示如何使用react-beautiful-dnd创建可拖拽表格,支持拖拽列、行和单元格:
import React, { useState } from 'react';
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';
const data = [
{ id: 1, name: 'Ap
pl
e', price: '$1' },
{ id: 2, name: 'Banana', price: '$2' },
{ id: 3, name: 'Orange', price: '$3' },
const Table = () => {
const [rows, setRows] = useState(data);
const handleDragEnd = (result) => {
const { source, destination } = result;
if (!destination) {
return;
const newRows = [...rows];
const [removed] = newRows[source.index].items.splice(source.draggableId - 1, 1);
newRows[destination.index].items.splice(destination.draggableId - 1, 0, removed);
setRows(newRows);
return (
<DragDropContext onDragEnd={handleDragEnd}>
<table>
<tbody>
{rows.map((row, index) => (
<Droppable key={row.id} droppableId={row_${row.id}
} direction="horizontal">
{(provided) => (
{...provided.droppableProps}
ref={provided.innerRef}
<td></td>
{row.items.map((item, index) => (
<Draggable key={item.id} draggableId={item.id} index={index}>
{(provided) => (
{...provided.draggableProps}
{...provided.dragHandleProps}
ref={provided.innerRef}
{item.name}
</Draggable>
{provided.placeholder}
</Droppable>
</tbody>
</table>
</DragDropContext>
export default Table;