实现拖拽复制和可排序的react.js组件

在实现复制前,对之前的拖拽排序组件属性进行了修改。

  1. 摒弃了value中的content属性,拖拽组件暴露的render函数,利用这个属性进行组件内部子组件的渲染,这点主要是参考了蚂蚁金服的Ant design里面一些组件的设计。
  2. 为了实现Data和model的脱藕,和sortKey一样,组件增加codeKey属性。

拖拽复制的效果如下:
图片描述

由于实现组件的核心是根据value数据来渲染页面,因此实现拖拽复制功能,只需要在“拖拽释放”的时候,将被拖拽方的数据放到当前目标所在的value数组中即可。

具体实现代码如下:

    // 当一个元素或是选中的文字被拖拽释放到一个有效的释放目标位置时
    drop(dropedSort, data, sortKey, dropedUid, codeKey, ee) {
        ee.preventDefault();
        const code = ee.dataTransfer.getData("code");
        const uId = ee.dataTransfer.getData("uId");
        const dragedItem = ee.dataTransfer.getData("item");
        const sort = ee.dataTransfer.getData("sort");
        if (uId === dropedUid) {
            if (sort < dropedSort) {
                data.map(item => {
                    if (item[codeKey] === code) {
                        item[sortKey] = dropedSort;
                    } else if (item[sortKey] > sort && item[sortKey] < dropedSort + 1) {
                        item[sortKey]--;
                    }
                    return item;
                });
            } else {
                data.map(item => {
                    if (item[codeKey] === code) {
                        item[sortKey] = dropedSort;
                    } else if (item[sortKey] > dropedSort - 1 && item[sortKey] < sort) {
                        item[sortKey]++;
                    }
                    return item;
                });
            }
        } else if (this.props.isAcceptAdd) {
            let objDragedItem = JSON.parse(dragedItem);
            if (data.filter(item => item[codeKey] === objDragedItem[codeKey]).length === 0) {
                const maxSort = Math.max.apply(Math, data.map(citem => citem[sortKey]));
                data.map(item => {
                    if (dropedSort === maxSort) {
                        objDragedItem[sortKey] = dropedSort + 1;
                    } else {
                        if (item.sort > dropedSort) {
                            objDragedItem[sortKey] = dropedSort + 1;
                            item[sortKey]++
                        }
                    }
                    return item
                });
                data.push(objDragedItem)
            }
        }
        this.props.onChange(data)
        if (ee.target.className.indexOf('droppingContent') !== -1) {
            ee.target.className = styles.droppedcontent;
        }
    }

这里要注意的有两点:
第一点是,我通过this.props.isAcceptAdd这个属性来判断当前组件是否允许接受拖拽复制的元素。
第二点是,我有一个放在内存中的“uId”,这个“uId”在每个拖拽组件初始化的时候生成。这样我就可以通过它来判断,当前被拖拽到目标区域的元素,是组件本身的内部元素还是外部元素,如果是内部就执行排序功能,外部则执行复制的逻辑代码。
组件API:
图片描述
GitHub地址:https://github.com/VicEcho/VD...

猜你喜欢

转载自www.cnblogs.com/10manongit/p/12769097.html