react-beautiful-dnd 横纵排序demo
【代码】react-beautiful-dnd 横纵排序demo。
·
简单导入就可以看到效果
1. 安装依赖
npm i react-beautiful-dnd
2. 纵向排序
import React, { useState } from 'react';
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';
// 纵向排序
const reorder = (list, startIndex, endIndex) => {
const result = Array.from(list);
const [removed] = result.splice(startIndex, 1);
result.splice(endIndex, 0, removed);
return result;
};
const DirectGrid = () => {
const [items, setItems] = useState(['Item 1', 'Item 2', 'Item 3', 'Item 4']);
const onDragEnd = (result) => {
// 如果没有目标位置,直接返回不执行任何操作
if (!result.destination) return;
// 使用Hook中的state进行reorder操作
const newItems = reorder(items, result.source.index, result.destination.index);
setItems(newItems);
};
return (
<DragDropContext onDragEnd={onDragEnd}>
<Droppable droppableId="droppable" direction="vertical">
{(provided) => (
<div {...provided.droppableProps} ref={provided.innerRef}>
{items.map((item, index) => (
<Draggable key={item} draggableId={item} index={index}>
{(provided) => (
<div
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
>
{item}
</div>
)}
</Draggable>
))}
{provided.placeholder}
</div>
)}
</Droppable>
</DragDropContext>
);
};
export default DirectGrid;
3. 横向排序
import React from 'react';
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';
// 横向排序
const reorder = (list, startIndex, endIndex) => {
const result = Array.from(list);
const [removed] = result.splice(startIndex, 1);
result.splice(endIndex, 0, removed);
return result;
};
const Grid = () => {
const [items, setItems] = React.useState([
{ id: '1', content: 'Item 1' },
{ id: '2', content: 'Item 2' },
{ id: '3', content: 'Item 3' },
// ...more items
]);
const onDragEnd = (result) => {
if (!result.destination) return;
const items = reorder(
this.state.items,
result.source.index,
result.destination.index
);
setItems(items);
};
return (
<DragDropContext onDragEnd={onDragEnd}>
<Droppable droppableId="droppable">
{(provided) => (
<div ref={provided.innerRef} {...provided.droppableProps}>
{items.map((item, index) => (
<Draggable key={item.id} draggableId={item.id} index={index}>
{(provided, snapshot) => (
<div
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
style={getItemStyle(
snapshot.isDragging,
provided.draggableProps.style
)}
>
{item.content}
</div>
)}
</Draggable>
))}
{provided.placeholder}
</div>
)}
</Droppable>
</DragDropContext>
);
};
const getItemStyle = (isDragging, draggableStyle) => ({
// some basic styles to apply when dragging
userSelect: 'none',
padding: 10,
margin: `0 0 ${isDragging ? 4 : 0}px 0`,
// change background colour if dragging
background: isDragging ? 'lightgreen' : 'lightblue',
// styles we need to apply on draggables
...draggableStyle,
});
export default Grid;
更多推荐
已为社区贡献4条内容
所有评论(0)