要使用React拖拽排序組件,首先需要安裝相關的庫。最常用的庫是react-dnd
和react-dnd-html5-backend
。
npm install react-dnd react-dnd-html5-backend
react-dnd
提供的DragSource
和DropTarget
高階組件來實現拖拽功能。import { DragSource, DropTarget } from "react-dnd";
const ItemTypes = {
CARD: "card"
};
// 創建一個DragSource
const cardSource = {
beginDrag(props) {
return {
id: props.id,
index: props.index
};
}
};
const collectDragSource = (connect, monitor) => {
return {
connectDragSource: connect.dragSource(),
isDragging: monitor.isDragging()
};
};
// 創建一個DropTarget
const cardTarget = {
drop(props, monitor) {
const dragIndex = monitor.getItem().index;
const hoverIndex = props.index;
// 在這里可以調用一個回調函數來更新排序
props.onMove(dragIndex, hoverIndex);
}
};
const collectDropTarget = (connect, monitor) => {
return {
connectDropTarget: connect.dropTarget()
};
};
// 最終的可拖拽組件
const DraggableCard = ({ text, isDragging, connectDragSource, connectDropTarget }) => {
return connectDragSource(
connectDropTarget(
<div style={{ opacity: isDragging ? 0.5 : 1 }}>
{text}
</div>
)
);
};
export default DragSource(ItemTypes.CARD, cardSource, collectDragSource)(
DropTarget(ItemTypes.CARD, cardTarget, collectDropTarget)(DraggableCard)
);
import { useState } from "react";
import update from "immutability-helper";
import DraggableCard from "./DraggableCard";
const SortableList = () => {
const [cards, setCards] = useState([
{ id: 1, text: "Card 1" },
{ id: 2, text: "Card 2" },
{ id: 3, text: "Card 3" }
]);
const handleMoveCard = (dragIndex, hoverIndex) => {
const dragCard = cards[dragIndex];
setCards(
update(cards, {
$splice: [
[dragIndex, 1],
[hoverIndex, 0, dragCard]
]
})
);
};
return (
<div>
{cards.map((card, index) => (
<DraggableCard
key={card.id}
id={card.id}
index={index}
text={card.text}
onMove={handleMoveCard}
/>
))}
</div>
);
};
export default SortableList;
SortableList
組件。import SortableList from "./SortableList";
const App = () => {
return (
<div>
<h1>Sortable List</h1>
<SortableList />
</div>
);
};
export default App;
現在,你就可以在應用中使用拖拽排序組件了。當你拖拽一個卡片并放置到另一個位置時,列表將會重新排序。