react-beautiful-dnd高级拖拽 之 自建DEMO

1.安装

yarn add react-beautiful-dnd

2.引入页面

renderNewList.ts

import React, { useEffect, useState } from 'react';
import { DragDropContext, Droppable, Draggable } from "react-beautiful-dnd";
import { reorderQuoteMap } from './renderNewList'

3.设置样式

/**
 * css样式--- 每一行样式
*/

const getListStyle = (isDraggingOver: any) => ({
  display: 'flex',
  height: height52,
  boxSizing: 'border-box',
});

const getItemStyle = (isDragging: any, draggableStyle: any) => ({
  padding: borderWidth * 2,
  boxSizing: 'border-box',
  background: '#989898',
  width: width220,
  height: height45,
  borderRadius: grid,
  margin: `${margin2}px 0`,
  // styles we need to apply on draggables需要在拖拽表上应用的样式
  ...draggableStyle,
});

4.ts


  // 二维数组
  const [isItemsArr, setIsItemsArr] = useState<{}>({
    droppable1: [
      { id: 'lmy-0', content: 'hello-不能拖', color: 'yellow', dragAble: 'false' },
      { id: 'lmy-1', content: '六-不能拖', color: 'red', dragAble: 'false' },
      { id: 'lmy-2', content: '6', color: 'green' },
      { id: 'lmy-3', content: '大', color: 'blue' },
      { id: 'lmy-4', content: '白', color: 'white' },
      { id: 'lmy-5', content: '鹅', color: 'purple' },
    ]
    ,
    droppable2: [
      { id: '66-0', content: '我-不能拖', color: 'red', dragAble: 'false' },
      { id: '66-1', content: '想-不能拖', color: 'red', dragAble: 'false' },
      { id: '66-2', content: '吃', color: 'red' },
      { id: '66-3', content: '火', color: 'red' },
      { id: '66-4', content: '锅', color: 'red' },
    ] })


 const [isDragDisabled, setIsDragDisabled] = useState(false)
 
  // 在拖动开始之前
  const onBeforeDragStart = (result: any) => {
    console.log('在拖动开始之前', result);
    const dragAble: any = isItemsArr[result.source.droppableId][result.source.index].dragAble
    if (dragAble) {
      console.log('不能拖');
      setIsDragDisabled(true)
    } else {
      console.log('能拖能拖能拖能拖');
      setIsDragDisabled(false)
    }
  }



  // 在拖动结束时
  const onDragEnd = (result: any) => {
    console.log('拖动结束时result-lmy', result, '-------', isItemsArr["droppable0"].length)
    
    // dropped outside the list//被排除在名单之外
    if (!result.destination) {
      return;
    }

  
      //判断能不能放到这个位置
      const isLast = isItemsArr[result.destination.droppableId]
      console.log('是不是最后一个元素', isLast[result.destination.index])
      
      if (isLast[result.destination.index]) {
        const hasDragAble = isItemsArr[result.destination.droppableId][result.destination.index]
        if (hasDragAble.dragAble) {
          console.log('不能放');
          return;
        }
      }

    const items = reorderQuoteMap(
      isItemsArr,
      result.source,
      result.destination
    );
    
    setIsItemsArr(items)
    console.log('items', items)
  }

5.页面搭建

  <div className="lmy">
     <DragDropContext onDragEnd={onDragEnd} onBeforeDragStart={onBeforeDragStart}>
         {/* 内容数据 */}
          <div className="hsc-lmy">
            {/* 每一行内容 */}
            <div className="column-lmy">
              <Droppable droppableId="droppable1" direction="horizontal">
                {(provided: any, snapshot: any) => (
                  <div
                    ref={provided.innerRef}
                    style={getListStyle(snapshot.isDraggingOver)}
                    {...provided.droppableProps}
                  >
                    {(isItemsArr['droppable1']).map((item: any, index: any) => (

                      <Draggable
                        isDragDisabled={item.dragAble ? true : false}
                        key={item.id} draggableId={item.id} index={index}>
                        {(provided: any, snapshot: any) => (
                          <div
                            className='lmy-item'
                            ref={provided.innerRef}
                            {...provided.draggableProps}
                            {...provided.dragHandleProps}
                            style={getItemStyle(
                              snapshot.isDragging,
                              provided.draggableProps.style

                            )}
                          >
                            {item.content}
                          </div>
                        )}
                      </Draggable>
                    ))}
                    {provided.placeholder}
                  </div>
                )}
              </Droppable>
            </div>
                   <div className="column-lmy">
                  <Droppable droppableId="droppable2" direction="horizontal">
                    {(provided: any, snapshot: any) => (
                      <div
                        ref={provided.innerRef}
                        style={getListStyle(snapshot.isDraggingOver)}
                        {...provided.droppableProps}
                      >
                        {isItemsArr['droppable2'].map((item: any, index: any) => (
                          <Draggable
                            isDragDisabled={item.dragAble ? true : false}
                            key={item.id} draggableId={item.id} index={index}>
                            {(provided: any, snapshot: any) => (
                              <div
                                ref={provided.innerRef}
                                {...provided.draggableProps}
                                {...provided.dragHandleProps}
                                style={getItemStyle(
                                  snapshot.isDragging,
                                  provided.draggableProps.style
                                )}>
                                {item.content}
                              </div>
                            )}
                          </Draggable>
                        ))}

                        {provided.placeholder}
                      </div>
                    )}
                  </Droppable>
                </div>
          </div>
      </DragDropContext>
  </div>

我这个小demo只是最初版,优化啥的我就不放了,涉及到项目隐私。

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
React-beautiful-dnd是一个React组件库,用于实现漂亮且易于使用的拖放列表。要实现一个列表拖放,需要执行以下步骤: 1. 安装react-beautiful-dnd: ``` npm install --save react-beautiful-dnd ``` 2. 导入DragDropContext、Droppable和Draggable组件: ```javascript import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd'; ``` 3. 创建状态并为每个列表项目分配一个唯一标识符: ```javascript const [items, setItems] = useState([ { id: "1", content: "Item 1" }, { id: "2", content: "Item 2" }, { id: "3", content: "Item 3" }, { id: "4", content: "Item 4" }, { id: "5", content: "Item 5" }, { id: "6", content: "Item 6" } ]); ``` 4. 创建渲染函数以呈现每个拖动项目: ```javascript const renderItems = () => { return 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> )); }; ``` 5. 创建渲染函数以呈现拖放列表: ```javascript const renderList = () => { return ( <DragDropContext onDragEnd={onDragEnd}> <Droppable droppableId="items"> {(provided, snapshot) => ( <div {...provided.droppableProps} ref={provided.innerRef} style={getListStyle(snapshot.isDraggingOver)}> {renderItems()} {provided.placeholder} </div> )} </Droppable> </DragDropContext> ); }; ``` 6. 创建onDragEnd函数以处理拖动项目: ```javascript const onDragEnd = result => { if (!result.destination) { return; } const itemsCopy = [...items]; const [reorderedItem] = itemsCopy.splice(result.source.index, 1); itemsCopy.splice(result.destination.index, 0, reorderedItem); setItems(itemsCopy); }; ``` 7. 创建样式函数以获取拖动和放置元素的样式: ```javascript const getItemStyle = (isDragging, draggableStyle) => ({ userSelect: 'none', padding: 16, margin: `0 0 ${8}px 0`, border: isDragging ? '2px solid #000' : 'none', ...draggableStyle }); const getListStyle = isDraggingOver => ({ background: isDraggingOver ? 'lightblue' : '#eee', padding: 8, width: 250 }); ``` 最后,用renderList函数渲染列表,将其放在你的React组件中,就可以开始拖放操作了!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值