import React, { useState } from "react";
import ReactDOM from "react-dom";
import styled from "@emotion/styled";
import { DragDropContext, Droppable, Draggable } from "react-beautiful-dnd";
import type { Quote as QuoteType } from "../types";
// 生成一个数组
const initial = Array.from({ length: 10 }, (v, k) => k).map(k => {
const custom: Quote = {
id: `id-${k}`,
content: `Quote ${k}`
};
return custom;
});
const grid = 8;
// 这个是控制拖拽的(第一个参数是一个数组,第二个参数是没移动前的位子,第三个参数是移动后的位子)
const reorder = (list, startIndex, endIndex) => {
const result = Array.from(list);
const [removed] = result.splice(startIndex, 1);
result.splice(endIndex, 0, removed);
return result;
};
// 这是是控制 这个组件颜色的
const QuoteItem = styled.div`
width: 400px;
border: 1px solid grey;
margin-bottom: ${grid}px;
background-color: lightblue;
padding: ${grid}px;
`;
function Quote({ quote, index }) {
return (
<Draggable draggableId={quote.id} index={index}>
{provided => (
<QuoteItem
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
>
{quote.content}
</QuoteItem>
)}
</Draggable>
);
}
//这个是组件
const QuoteList = React.memo(function QuoteList({ quotes }) {
return quotes.map((quote: QuoteType, index: number) => (
<Quote quote={quote} index={index} key={quote.id} />
));
});
function QuoteApp() {
const [state, setState] = useState({ quotes: initial });
function onDragEnd(result) {
if (!result.destination) {
return;
}
if (result.destination.index === result.source.index) {
return;
}
const quotes = reorder(
state.quotes,
result.source.index,
result.destination.index
);
setState({ quotes });
}
return (
<DragDropContext onDragEnd={onDragEnd}>
<Droppable droppableId="list">
{provided => (
<div ref={provided.innerRef}
{...provided.droppableProps}>
<QuoteList quotes={state.quotes} />
{/*{provided.placeholder}*/}
</div>
)}
</Droppable>
</DragDropContext>
);
}
export default QuoteApp
基于react的拖拽组件库react-beautiful-dnd 与功能组件一起使用
最新推荐文章于 2024-04-23 17:19:53 发布