react-beautiful-dnd 横纵排序demo

react-beautiful-dnd 横纵排序demo

码农世界 2024-05-31 后端 75 次浏览 0个评论

简单导入就可以看到效果

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 (
    
      
        {(provided) => (
          
            {items.map((item, index) => (
              
                {(provided) => (
                  
                    {item}
                  
                )}
              
            ))}
            {provided.placeholder}
          
        )}
      
    
  );
};
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 (
    
      
        {(provided) => (
          
            {items.map((item, index) => (
              
                {(provided, snapshot) => (
                  
                    {item.content}
                  
                )}
              
            ))}
            {provided.placeholder}
          
        )}
      
    
  );
};
 
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;

转载请注明来自码农世界,本文标题:《react-beautiful-dnd 横纵排序demo》

百度分享代码,如果开启HTTPS请参考李洋个人博客
每一天,每一秒,你所做的决定都会改变你的人生!

发表评论

快捷回复:

评论列表 (暂无评论,75人围观)参与讨论

还没有评论,来说两句吧...

Top