React +TS实现拖拽列表
在React和TypeScript中实现一个简单的拖拽列表,你可以使用react-beautiful-dnd
库。以下是一个简单的实现例子:
首先,安装react-beautiful-dnd
:
npm install react-beautiful-dnd
然后,你可以创建一个简单的拖拽列表组件:
import React, { useState } from 'react';
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';
const reorder = (list: any[], startIndex: number, endIndex: number) => {
const result = Array.from(list);
const [removed] = result.splice(startIndex, 1);
result.splice(endIndex, 0, removed);
return result;
};
const DraggableList: React.FC = () => {
const [items, setItems] = useState([
{ id: '1', content: 'Item 1' },
{ id: '2', content: 'Item 2' },
{ id: '3', content: 'Item 3' },
// ...
]);
const onDragEnd = (result: any) => {
if (!result.destination) return;
const itemsCopy = [...items];
const reordered = reorder(
itemsCopy,
result.source.index,
result.destination.index
);
setItems(reordered);
};
return (
<DragDropContext onDragEnd={onDragEnd}>
<Droppable droppableId="droppable">
{(provided) => (
<div {...provided.droppableProps} ref={provided.innerRef}>
{items.map((item: any, index: number) => (
<Draggable key={item.id} draggableId={item.id} index={index}>
{(provided) => (
<div
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
>
{item.content}
</div>
)}
</Draggable>
))}
{provided.placeholder}
</div>
)}
</Droppable>
</DragDropContext>
);
};
export default DraggableList;
在这个例子中,DragDropContext
提供了拖拽操作所需的上下文,Droppable
是一个可以放置Draggable
项的区域,Draggable
是可拖动的列表项。reorder
函数用于重新排列列表项。当拖动结束时,onDragEnd
会根据拖动的结果重新排列状态中的items
数组。
评论已关闭