摘要:最近在做会议系统,9宫格小画面要支持拖拽调整顺序,需求已经实现了,简单记录下当时的逻辑处理。
/*=========== 关于拖拽逻辑处理 start ========= */
// 当前在拖动的下标
const curDragIndex = useRef<number>(-1);
/* 拖拽元素事件
* onDragStart_开始
* onDragend_结束
*/
const handleDragStart = (event: any, index: number) => {
curDragIndex.current = index;
onDropStart(index);
};
const handleDragend = (event: any, index: number) => {
event.preventDefault();
}
/* 放置元素事件
* onDragEnter_进入放置目标时
* onDragover_在放置目标中移动时
* onDragleave_离开放置目标时
* onDrag_放置在目标上并释放时
*/
const handleOnDragEnter = (event: any, index: number) => {
// 阻止默认处理(不允许放置)
event.preventDefault();
}
const handleOnDragLeave = (event: any, index: number) => {
// 阻止默认处理(不允许放置)
event.preventDefault();
}
const handleOnDragOver = (event: any, index: number) => {
// 阻止默认处理(不允许放置)
event.preventDefault();
}
const handleOnDrop = (event: any, index: number) => {
event.preventDefault();
// 处理拖拽交换
hadnleSwitchItem(curDragIndex.current, index);
}
/*====== 关于拖拽逻辑处理 end ================ */
// 成员列表
const [memberList, setMemberList] = useState([
{name: 'yyh1', id: 1},
{name: 'yyh2', id: 2},
]);
/* 处理拖拽交换
curIndex: 0, 类型: number; 说明: 拖拽的下标
tranIndex: 1, 类型: number; 说明: 被释放的下班
*/
const hadnleSwitchItem = (curIndex, tranIndex) => {
const old = memberList[curIndex];
// 交换位置
memberList[curIndex] = memberList[tranIndex];
memberList[tranIndex] = old;
// 更新数据
setMemberList([...memberList]);
};
/* tsx 页面渲染 */
memberList.map((item, index) => {
return <div key={index} className={`${style['user_item_' + (index + 1)]}`}
draggable={true}
onDragStart={(event) => handleDragStart(event, index)}
onDragEnd={(event: any) => handleDragend(event, index)}
onDragEnter={(event) => handleOnDragEnter(event, index)}
onDragLeave={(event) => handleOnDragLeave(event, index)}
onDragOver={(event) => handleOnDragOver(event, index)}
onDrop={(event: any) => handleOnDrop(event, index)}
>
</div>
});