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

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

拖拽复制的效果如下:

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

由于实现组件的核心是根据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:

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


GitHub地址:https://github.com/VicEcho/VDraggable

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/a7edac631e81fb44605281a2dd9e3b1e.html