// 用的时候先安装react-beautiful-dnd
import React, {Component} from "react";
import {DragDropContext, Droppable, Draggable} from "react-beautiful-dnd";
// 生成一个数组
const getItems = (count:any) =>
Array.from({length: count}, (v, k) => k).map(k => ({
id: `item-${k}`,
content: `item ${k}`
}));
// 这个方法是专门更改拖拽之后换位子的
const reorder = (list:any, startIndex:any, endIndex:any) => {
const result = Array.from(list);
console.log(result,'11111111111111')
const [removed] = result.splice(startIndex, 1);
result.splice(endIndex, 0, removed);
return result;
};
class Index extends Component {
constructor(props:any) {
super(props);
this.state = {
items: getItems(5)
};
this.onDragEnd = this.onDragEnd.bind(this);
}
onDragEnd(result:any) {
console.log(result)
if (!result.destination) {
return;
}
const items = reorder(
this.state.items,
result.source.index,
result.destination.index
);
this.setState({
items
});
}
render() {
return (
<DragDropContext onDragEnd={this.onDragEnd}>
<Droppable droppableId="droppable">
{(provided:any, snapshot:any) => (
<div
{...provided.droppableProps}
ref={provided.innerRef}
>
{this.state.items.map((item:any, index:any) => (
<Draggable key={item.id} draggableId={item.id} index={index}>
{(provided:any, snapshot:any) => (
<div
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
>
{item.content}1111
</div>
)}
</Draggable>
))}
</div>
)}
</Droppable>
</DragDropContext>
);
}
}
export default Index;