如何实现如下场景:对列表的列表项进行拖动时,其他列表项自动补位和动态排列的效果
要实现列表项拖动时其他列表项自动补位和动态排列的效果,你可以使用前端 JavaScript 库来实现这个功能。其中一个流行的库是 react-beautiful-dnd
,它专为 React 构建,用于实现拖放功能。
以下是使用 react-beautiful-dnd
实现该功能的基本步骤:
npm install react-beautiful-dnd
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';
items
。DragDropContext
、Droppable
和 Draggable
组件:<DragDropContext onDragEnd={handleDragEnd}>
<Droppable droppableId="droppable">
{(provided) => (
<ul {...provided.droppableProps} ref={provided.innerRef}>
{items.map((item, index) => (
<Draggable key={item.id} draggableId={item.id} index={index}>
{(provided) => (
<li
{...provided.draggableProps}
{...provided.dragHandleProps}
ref={provided.innerRef}
>
{item.content}
</li>
)}
</Draggable>
))}
{provided.placeholder}
</ul>
)}
</Droppable>
</DragDropContext>
onDragEnd
):onDragEnd
回调来更新你的 items
数组,使其反映新的顺序。const handleDragEnd = (result) => {
if (!result.destination) return;
const itemsArray = Array.from(items);
const [reorderedItem] = itemsArray.splice(result.source.index, 1);
itemsArray.splice(result.destination.index, 0, reorderedItem);
setItems(itemsArray);
};
上述步骤为你提供了一个基本的框架来实现列表项的拖放功能,其中其他列表项会自动补位和动态排列。当然,根据你的具体需求,你可能需要调整或扩展这些代码。
1 回答920 阅读✓ 已解决
1 回答1.2k 阅读
1 回答1k 阅读
1 回答985 阅读
1 回答957 阅读
1 回答851 阅读
1 回答812 阅读