简单导入就可以看到效果
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 (); }; export default DirectGrid; {(provided) => ( {items.map((item, index) => ( {(provided) => ( {item} )} ))} {provided.placeholder} )}
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 (); }; 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; {(provided) => ( {items.map((item, index) => ( {(provided, snapshot) => ( {item.content} )} ))} {provided.placeholder} )}
还没有评论,来说两句吧...