react拖拽react-beautiful-dnd一维数组二维数组拖拽功能

 更新时间:2024年03月25日 09:46:33   作者:避坑记录  
二维数组可以拖拽,但是不可以编辑+拖拽,如果想要实现编辑+拖拽,还是需要转换成一维数组,本文给大家介绍react拖拽react-beautiful-dnd的相关知识,感兴趣的朋友跟随小编一起看看吧
(福利推荐:【腾讯云】服务器最新限时优惠活动,云服务器1核2G仅99元/年、2核4G仅768元/3年,立即抢购>>>:9i0i.cn/qcloud

(福利推荐:你还在原价购买阿里云服务器?现在阿里云0.8折限时抢购活动来啦!4核8G企业云服务器仅2998元/3年,立即抢购>>>:9i0i.cn/aliyun

写在前边,二维数组可以拖拽,但是不可以编辑+拖拽,如果想要实现编辑+拖拽,还是需要转换成一维数组。原因是因为插件的官方规定,在拖拽过程中不可以编辑Droppable层的Props。

相关地址:

中文文档地址

react-beautiful-dnd - 《react-beautiful-dnd 中文文档帮助手册教程》 - 极客文档 (geekdaxue.co)

git源码

GitHub - chinanf-boy/react-beautiful-dnd-zh: ??翻译: react-beautiful-dnd 文档 ?? 更新 ?

使用

安装

# yarn
yarn add react-beautiful-dnd
# npm
npm install react-beautiful-dnd --save

引入

import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';

引用

<DraggableList data={listDemo}></DraggableList>

一维数组使用

传参data是一维数组

import React, { useEffect, useState } from 'react';
import { DragDropContext, Draggable, Droppable } from 'react-beautiful-dnd';
interface Props {
  data: any[];
}
const DraggableList: React.FC<Props> = ({ data }) => {
  const [sortList, setSortList] = useState([]);
  const getItems = () => {
    const arr = Array.from({ length: 10 }, (v, k) => k).map((k) => ({
      id: `item-${k}`,
      content: `item ${k}`,
    }));
    setSortList(arr);
  };
  useEffect(() => {
    getItems();
  }, []);
  const grid = 8;
  const getItemStyle = (isDragging, draggableStyle) => ({
    // some basic styles to make the items look a bit nicer
    userSelect: 'none',
    padding: grid * 2,
    margin: `0 ${grid}px 0 0`,
    // change background colour if dragging
    background: isDragging ? 'lightgreen' : 'grey',
    // styles we need to apply on draggables
    ...draggableStyle,
  });
  const getListStyle = (isDraggingOver: any) => ({
    background: isDraggingOver ? 'lightblue' : 'lightgrey',
    display: 'flex',
    padding: grid,
    overflow: 'auto',
  });
  const onDragEnd = (result) => {
    if (!result.destination) {
      return;
    }
    console.log('end', sortList, result);
    const res = sortList.filter((item) => item); // 更改引用地址
    console.log('移动前res', res);
    const [removed] = res.splice(result.source.index, 1);
    console.log('删除???', removed);
    res.splice(result.destination.index, 0, removed);
    console.log('添加后', res);
    setSortList(res);
  };
  console.log('data', data);
  /**
   * Draggable组件可以拖动并拖放到其Droppables上. 一个Draggable必须始终包含在一个Droppable.
   * 它是 可能重新排序Draggable在其Droppable家中或移动到另一个Droppable.
   * 一个Draggable必须包含在一个Droppable.
   * */
  return (
    <DragDropContext onDragEnd={onDragEnd}>
      <Droppable droppableId="droppable" direction="horizontal">
        {(provided, snapshot) => (
          <div ref={provided.innerRef} style={getListStyle(snapshot.isDraggingOver)} {...provided.droppableProps}>
            {sortList.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>
  );
};
export default DraggableList;

二维数组的使用

import React, { useEffect, useState } from 'react';
import { DragDropContext, Draggable, Droppable } from 'react-beautiful-dnd';
interface Props {
  data: any[];
}
const DraggableList: React.FC<Props> = ({ data = [] }) => {
  const [sortList, setSortList] = useState(data);
  const grid = 8;
  const getItemStyle = (isDragging, draggableStyle) => ({
    // some basic styles to make the items look a bit nicer
    userSelect: 'none',
    padding: grid * 2,
    margin: `0 ${grid}px 0 0`,
    // change background colour if dragging
    background: isDragging ? 'lightgreen' : 'grey',
    // styles we need to apply on draggables
    ...draggableStyle,
  });
  const getListStyle = (isDraggingOver) => ({
    background: isDraggingOver ? 'lightblue' : 'lightgrey',
    display: 'flex',
    padding: grid,
    overflow: 'auto',
  });
  const onDragEnd = (result) => {
    if (!result.destination) {
      return;
    }
    console.log('end', sortList, result);
    const res = sortList.filter((item) => item); //修改引用地址
    console.log('res', res);
    const [removed] = res.splice(result.source.index, 1);
    console.log('删除???', removed);
    res.splice(result.destination.index, 0, removed);
    console.log('添加后', res);
    setSortList(res);
  };
  useEffect(() => {
    setSortList(data);
  }, [data]);
  console.log('data', data);
  return (
    <DragDropContext onDragEnd={onDragEnd}>
      {sortList.map((item, index) => {
        return (
          <Droppable droppableId={'droppable' + index} key={index} direction="vertical">
            {(provided, snapshot) => (
              <div ref={provided.innerRef} style={getListStyle(snapshot.isDraggingOver)} {...provided.droppableProps}>
                {/*{data.map((item, index) => (*/}
                <Draggable key={item[0].value} draggableId={item[0].value} index={index}>
                  {(provided, snapshot) => (
                    <div
                      ref={provided.innerRef}
                      {...provided.draggableProps}
                      {...provided.dragHandleProps}
                      style={getItemStyle(snapshot.isDragging, provided.draggableProps.style)}
                    >
                      {66666 + item[0].label}
                    </div>
                  )}
                </Draggable>
                {/*))}*/}
                {provided.placeholder}
              </div>
            )}
          </Droppable>
        );
      })}
    </DragDropContext>
  );
};
export default DraggableList;

组件传值的数组内容 

  const [options, setOptions] = useState([
    {
      label: '延时时间',
      value: 'delayTime',
      children: [
        {
          label: '时',
          value: 'hour',
          disabled: false,
        },
        {
          label: '分',
          value: 'minute',
          disabled: false,
        },
        {
          label: '秒',
          value: 'second',
          disabled: false,
        },
      ],
    },
    {
      label: '限制类型',
      value: 'limitType',
      children: [
        {
          label: '前置点位1',
          value: '1',
          disabled: false,
        },
        {
          label: '前置点位2',
          value: '2',
          disabled: false,
        },
        {
          label: '前置点位3',
          value: '3',
          disabled: false,
        },
      ],
    },
    {
      label: '温度',
      value: 'templete',
    },
  ]);

案列

案例是通过级联的组件选择条件,新增条件时,前端重新定义数据格式,将二维的结构改成一维数组的结构。遍历填充内容时,是在Droppable的下一级,所以可以修改内容。

  const onDispatchValue = (res: any) => {
    dispatch({
      type: `${MODEL_NAME}/save`,
      payload: {
        proTypeList: res,
      },
    });
  }; 
// 新增、删除前置条件
  const [inputFlag, setInputFlag] = useState(false);
  const [listDemo, setListDemo] = useState([]);
  const changeCondition = (ids, option) => {
    let arr2 = [];
    // 第三层关系选中两个时的判断
    if (ids && ids.length > 1) {
      // 二维数组结构成一维数组,方便去重
      arr2 = ids.reduce((a, b) => {
        return a.concat(b);
      });
      const arr3 = Array.from(new Set(arr2));
      if (arr2.length !== arr3.length) {
        setRepeatFlag(true);
        return message.warning('前置条件重复,请删除!');
      } else {
        setRepeatFlag(false);
      }
    }
    // 没有子级或者全选的判断
    ids.map((item, index) => {
      if (item.length === 1 && option[index][0].value === item[0] && option[index][0]?.children?.length > 0) {
        setRepeatFlag(true);
        return message.warning('前置条件重复,请删除!');
      } else {
        setRepeatFlag(false);
      }
    });
    const arr = option.map((item) => {
      let obj = {
        typeName: '', // 类型名称
        typeValue: '', // 类型id
        unitName: '', // 单位名称
        unitValue: '', // 单位id
        value: '', // 值
      };
      item.map((i, index) => {
        if (item.length === 1) {
          obj.typeName = i.label;
          obj.typeValue = i.value;
        }
        if (item.length === 2) {
          if (index === 1) {
            obj.unitName = i.label;
            obj.unitValue = i.value;
          } else {
            obj.typeName = i.label;
            obj.typeValue = i.value;
          }
        }
      });
      return obj;
    });
    setListDemo(arr);
    // 保存定义好的数据,用于组件之间传值
    onDispatchValue(arr);
  };
// 父组件引用
<DraggableList data={proTypeList}></DraggableList>
// 子组件
import { ConnectState } from '@/typing/connect';
import { connect } from '@@/exports';
import { Input } from 'antd';
import React, { useEffect, useState } from 'react';
import { DragDropContext, Draggable, Droppable } from 'react-beautiful-dnd';
import { Dispatch } from 'umi';
interface Props {
  data: any[];
  dispatch: Dispatch;
}
const MODEL_NAME = 'mainConfig';
const DraggableList: React.FC<Props> = ({ data = [], dispatch }) => {
  const [sortList, setSortList] = useState(data);
  // 拖拽时的样式
  const getListStyle = () => ({
    overflow: 'auto',
    width: '100%',
  });
  // 拖拽后的样式
  const getItemStyle = (isDragging, draggableStyle) => ({
    // some basic styles to make the items look a bit nicer
    width: '100%',
    userSelect: 'none',
    ...draggableStyle,
  });
  const onDragEnd = (result) => {
    if (!result.destination) {
      return;
    }
    const res = sortList.filter((item) => item); //修改引用地址
    const [removed] = res.splice(result.source.index, 1);
    res.splice(result.destination.index, 0, removed);
    // console.log('添加后', res);
    setSortList(res);
    dispatch({
      type: `${MODEL_NAME}/save`,
      payload: {
        proTypeList: res,
      },
    });
    console.log('拖拽后', res);
  };
  // 校验输入框内容
  const regInputValue = (e: any, index: number) => {
    // 输入框聚焦时
    const arr = data.filter((item) => item);
    arr[index].value = e.target.value;
    console.log('arr', arr);
    setSortList(arr);
    dispatch({
      type: `${MODEL_NAME}/save`,
      payload: {
        proTypeList: arr,
      },
    });
  };
  useEffect(() => {
    setSortList(data);
  }, [data]);
  // console.log('弹窗起落data', data);
  /**
   * Draggable组件可以拖动并拖放到其Droppables上. 一个Draggable必须始终包含在一个Droppable.
   * 它是 可能重新排序Draggable在其Droppable家中或移动到另一个Droppable.
   * 一个Draggable必须包含在一个Droppable.
   * */
  return (
    <DragDropContext onDragEnd={onDragEnd}>
      <Droppable droppableId="droppable" direction="horizontal">
        {(provided, snapshot) => (
          <div ref={provided.innerRef} style={getListStyle(snapshot.isDraggingOver)} {...provided.droppableProps}>
            {data.map((item, index) => (
              <Draggable key={item.typeValue} draggableId={item.typeValue} index={index}>
                {(provided, snapshot) => (
                  <div
                    ref={provided.innerRef}
                    {...provided.draggableProps}
                    {...provided.dragHandleProps}
                    style={getItemStyle(snapshot.isDragging, provided.draggableProps.style)}
                  >
                    <div style={{ width: '100%', display: 'flex', justifyContent: 'flex-start', textAlign: 'center' }}>
                      <div style={{ width: '33%', backgroundColor: '#f2f2f2', padding: '8px 0' }}>条件名称</div>
                      <div style={{ width: '33%', backgroundColor: '#f2f2f2', padding: '8px 0' }}>条件值</div>
                      <div style={{ width: '33%', backgroundColor: '#f2f2f2', padding: '8px 0' }}>单位名称</div>
                    </div>
                    <div
                      style={{
                        width: '100%',
                        display: 'flex',
                        justifyContent: 'flex-start',
                        padding: '6px',
                        textAlign: 'center',
                        marginBottom: 16,
                      }}
                    >
                      <div style={{ width: '33%', padding: '8px 0' }}>{item.typeName}</div>
                      <div style={{ width: '33%', padding: '8px 0' }}>
                        <Input
                          placeholder="请输入内容"
                          onChange={(e) => {
                            regInputValue(e, index);
                          }}
                        />
                      </div>
                      <div style={{ width: '33%', padding: '8px 0' }}>{item.unitName}</div>
                    </div>
                  </div>
                )}
              </Draggable>
            ))}
            {provided.placeholder}
          </div>
        )}
      </Droppable>
    </DragDropContext>
  );
};
export default connect(({ mainConfig }: ConnectState) => ({
  mainConfig ,
}))(DraggableList);

到此这篇关于react拖拽react-beautiful-dnd,一维数组,二维数组的文章就介绍到这了,更多相关react拖拽react-beautiful-dnd,一维数组,二维数组内容请搜索程序员之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持程序员之家!

相关文章

  • VSCode配置react开发环境的步骤

    VSCode配置react开发环境的步骤

    本篇文章主要介绍了VSCode配置react开发环境的步骤,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-12-12
  • 使用React?SSR写Demo一学就会

    使用React?SSR写Demo一学就会

    这篇文章主要为大家介绍了使用React?SSR写Demo实现教程示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-06-06
  • react中ref获取dom或者组件的实现方法

    react中ref获取dom或者组件的实现方法

    这篇文章主要介绍了react中ref获取dom或者组件的实现方法,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-05-05
  • React实现核心Diff算法的示例代码

    React实现核心Diff算法的示例代码

    这篇文章主要为大家详细介绍了React如何实现Diff算法,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
    2022-04-04
  • react mobx 基本用法示例小结

    react mobx 基本用法示例小结

    mobx是一个轻量级的状态管理器,所以很简单(单一全局数据使用class)类有get 数据方法,本文通过示例代码介绍react mobx 基本用法,感兴趣的朋友有一起看看
    2023-11-11
  • 如何在React项目中引入字体文件并使用详解

    如何在React项目中引入字体文件并使用详解

    我们项目中通常会需要引入字体,所以下面这篇文章主要给大家介绍了关于如何在React项目中引入字体文件并使用的相关资料,文中通过图文介绍的非常详细,需要的朋友可以参考下
    2022-08-08
  • 图文示例讲解useState与useReducer性能区别

    图文示例讲解useState与useReducer性能区别

    这篇文章主要为大家介绍了useState与useReducer性能区别图文示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-05-05
  • React使用高德地图的实现示例(react-amap)

    React使用高德地图的实现示例(react-amap)

    这篇文章主要介绍了React使用高德地图的实现示例(react-amap),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-04-04
  • 基于React Context实现一个简单的状态管理的示例代码

    基于React Context实现一个简单的状态管理的示例代码

    本文主要介绍了基于React Context实现一个简单的状态管理的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-07-07
  • 详解React中函数式组件与类组件的不同

    详解React中函数式组件与类组件的不同

    React?函数式组件与类组件的主要区别在于它们的定义和声明方式以及它们之间的一些特性,所以本文就详细的给大家讲讲React中函数式组件与类组件有何不同,需要的朋友可以参考下
    2023-09-09

最新评论

?


http://www.vxiaotou.com