拖动改变顺序
效果: 将被拖动的元素放在拖动结束时的元素后面
实现
jsx
import React, { useState } from 'react';
import styles from './index.less';
let dragStartIndex = 0; // 记录被拖动的元素index
let dragEndIndex = 0; // 鼠标移动时,被悬浮的元素index
export default () => {
const [list, setLIst] = useState([]);
const [highLightIndex, setHighLightIndex] = useState(undefined); // 鼠标移动时被悬浮的元素(用来高亮定位)
// 拖动开始: 记录被拖动元素
const onDragStart = (index) => {
dragStartIndex = index;
};
// 拖动进入事件: 记录被悬浮的元素
const onDragEnter = (index) => {
dragEndIndex = index;
setHighLightIndex(index);
};
// 拖动结束:改变数组,去掉dragStartIndex,插入dragEndIndex后面位置;
const onDragEnd = () => {
if (dragEndIndex === dragStartIndex) {
setHighLightIndex(undefined);
return;
}
const tabHeadersCopy = [...list];
const dragingTab = tabHeadersCopy[dragStartIndex];
// 为了实现拖动元素放到被浮动的元素后面,从前往后拖动和从后往前拖动,增删数组稍有差异
if (dragEndIndex > dragStartIndex) {
tabHeadersCopy.splice(dragStartIndex, 1);
tabHeadersCopy.splice(dragEndIndex, 0, dragingTab);
} else {
tabHeadersCopy.splice(dragEndIndex + 1, 0, dragingTab);
tabHeadersCopy.splice(dragStartIndex + 1, 1);
}
setLIst(tabHeadersCopy);
setHighLightIndex(undefined);
};
return (
<div className={styles['tabs-container']}>
{list &&
list.length > 0 &&
list.map((tab, index) => (
<div
key={tab.id}
draggable={true}
onDragStart={() => onDragStart(index)}
onDragEnd={onDragEnd}
onDragEnter={() => onDragEnter(index)}
style={{ borderColor: index === highLightIndex ? 'red' : '' }}
>
{tab.name}
</div>
))}
</div>
);
};
参考实现: react中实现拖拽排序react-dnd