React Hook useDragList 列表拖拽
作者:互联网
Hook定义 useDragList
import { useState } from "react";
interface useDragPropsType {
list: Array<any>,
dragItemClassName: string
}
const checkValidDragItem = (e: React.DragEvent, className: string) => (e.target as HTMLLIElement).className === className
const useDragList = ({ list, dragItemClassName }: useDragPropsType) => {
const [dragList, setDragList] = useState(list)
const [curDragIndex, setCurDragIndex] = useState<number>(-1)
const handleDragStart = (e: React.DragEvent, index: number) => {
if (!checkValidDragItem(e, dragItemClassName)) return
setCurDragIndex(index)
}
// 需要在这里阻止默认事件,否则handleDrop不触发
const handleDragOver = (e: React.DragEvent) => {
if (!checkValidDragItem(e, dragItemClassName)) return
e.preventDefault()
}
const handleDrop = (e: React.DragEvent, index: number) => {
if (!checkValidDragItem(e, dragItemClassName)) return
[dragList[index], dragList[curDragIndex]] = [dragList[curDragIndex], dragList[index]] // swap
setDragList([...dragList])
}
return {
list:dragList,
handleDragStart,
handleDragOver,
handleDrop
}
}
export default useDragList
Hook使用
import useDragList from "../hooks/useDragList"
import './DragDemo.css'
interface dragItemType {
id: number | string
}
const dragListData: Array<dragItemType> = Array(4).fill('').map((v, i) => ({
id: i
}))
const dragItemClass = "dragItem"
const DragDemo: React.FC = () => {
const {
list: dragList,
handleDragStart,
handleDragOver,
handleDrop
} = useDragList({ list: dragListData, dragItemClassName: dragItemClass })
return (
<ul className="dragWrapper">
{
dragList.map((v, i) => (
<li className={dragItemClass}
draggable={true}
key={v.id}
onDragStart={(e) => handleDragStart(e, i)}
onDragOver={(e) => handleDragOver(e)}
onDrop={(e) => handleDrop(e, i)}
>{v.id}</li>
))
}
</ul>
)
}
export default DragDemo
标签:useDragList,list,React,Hook,dragList,dragItemClassName,const 来源: https://www.cnblogs.com/ltfxy/p/16386815.html