提示:可拖拽
提示:以下是本篇文章正文内容,下面案例可供参考
1.引入库
代码如下(示例):
import * as React from 'react'
import {
DragDropContext, Droppable, Draggable } from "react-beautiful-dnd";
const items = [
{
id: "1", content: "Card 1" },
{
id: "2", content: "Card 2" },
{
id: "3", content: "Card 3" },
{
id: "4", content: "Card 4" }
];
const Card = ({
item, index }) => {
return (
<Draggable draggableId={
item.id} index={
index}>
{
(provided, snapshot) => (
<div
className="card"
ref={
provided.innerRef}
{
...provided.draggableProps}
{
...provided.dragHandleProps}
style={
{
backgroundColor: snapshot.isDragging ? "lightblue" : "white",
...provided.draggableProps.style
}}
>
{
item.content}
</div>
)}
</Draggable>
);
};
const CardList = () => {
const [cards, setCards] = React.useState(items);
const onDragEnd = (result) => {
if (!result.destination) return;
const {
source, destination } = result;
const newCards = Array.from(cards);
const [removed] = newCards.splice(source.index, 1);
newCards.splice(destination.index, 0, removed);
setCards(newCards);
};
return (
<DragDropContext onDragEnd={
onDragEnd}>
<Droppable droppableId="cards">
{
(provided) => (
<div {
...provided.droppableProps} ref={
provided.innerRef}>
{
cards.map((card, index) => (
<Card key={
card.id} item={
card} index={
index} />
))}
{
provided.placeholder}
</div>
)}
</Droppable>
</DragDropContext>
);
};
export default CardList;