react - beautiful-dnd 写一个多行列表拖拽
时间: 2024-05-30 08:13:16 浏览: 149
好的,我可以为你提供以下代码示例来实现这个功能:
import React, { useState } from "react";
import { DragDropContext, Droppable, Draggable } from "react-beautiful-dnd";
const initialData = {
items: [
{ id: "item-1", content: "Item 1" },
{ id: "item-2", content: "Item 2" },
{ id: "item-3", content: "Item 3" },
{ id: "item-4", content: "Item 4" },
{ id: "item-5", content: "Item 5" },
{ id: "item-6", content: "Item 6" },
{ id: "item-7", content: "Item 7" },
{ id: "item-8", content: "Item 8" },
{ id: "item-9", content: "Item 9" },
{ id: "item-10", content: "Item 10" }
]
};
const MultiLineDragAndDrop = () => {
const [data, setData] = useState(initialData);
const handleDragEnd = result => {
const { destination, source, draggableId } = result;
if (!destination) {
return;
}
if (
destination.index === source.index &&
destination.droppableId === source.droppableId
) {
return;
}
const item = data.items.find(item => item.id === draggableId);
const newData = { ...data };
newData.items.splice(source.index, 1);
newData.items.splice(destination.index, 0, item);
setData(newData);
};
return (
<DragDropContext onDragEnd={handleDragEnd}>
<Droppable droppableId="multi-line-dnd">
{(provided, snapshot) => (
<ul
ref={provided.innerRef}
{...provided.droppableProps}
className="multi-line-dnd-list"
>
{data.items.map((item, index) => (
<Draggable key={item.id} draggableId={item.id} index={index}>
{(provided, snapshot) => (
<li
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
className={`multi-line-dnd-item ${
snapshot.isDragging ? "is-dragging" : ""
}`}
>
{item.content}
</li>
)}
</Draggable>
))}
{provided.placeholder}
</ul>
)}
</Droppable>
</DragDropContext>
);
};
export default MultiLineDragAndDrop;
请注意,上述代码示例仅为参考,并且需要安装 react-beautiful-dnd 库。还要在 css 文件中设置样式,以使其正确显示和工作。
阅读全文