如何阻止react-sortable-hoc中的网格项被拖拽出容器范围?
解决react-sortable-hoc拖拽项移出网格容器的问题
用
onSortMove回调限制拖拽范围
react-sortable-hoc自带的onSortMove钩子可以直接拦截拖拽动作,你只需要在这个函数里对比拖拽项和容器的边界,超出就返回false阻止移动。
示例代码:const onSortMove = ({ node, moveTo }) => { const container = document.getElementById('grid-container'); if (!container) return true; const containerRect = container.getBoundingClientRect(); const nodeRect = node.getBoundingClientRect(); // 计算拖拽项的目标位置 const targetLeft = containerRect.left + moveTo.x; const targetTop = containerRect.top + moveTo.y; // 检查是否在容器范围内(根据你的网格项尺寸调整判断逻辑) const notOutLeft = targetLeft >= containerRect.left; const notOutRight = targetLeft + nodeRect.width <= containerRect.right; const notOutTop = targetTop >= containerRect.top; const notOutBottom = targetTop + nodeRect.height <= containerRect.bottom; return notOutLeft && notOutRight && notOutTop && notOutBottom; }; // 给SortableContainer加上这个回调 const SortableGrid = SortableContainer(({ children }) => ( <div id="grid-container" className="grid"> {children} </div> ));视觉上通过容器样式兜底
给网格容器加overflow: hidden,同时把拖拽克隆体的父元素设为容器本身(用getGhostParent指定),这样就算拖拽逻辑有小偏差,克隆体也不会跑到容器外面显示。
示例:const SortableItem = SortableElement(({ value }) => ( <div className="grid-item">{value}</div> )); const SortableGrid = SortableContainer(({ items }) => ( <div className="grid" style={{ overflow: 'hidden', position: 'relative' }}> {items.map((value, index) => ( <SortableItem key={`item-${index}`} index={index} value={value} /> ))} </div> ), { getGhostParent: () => document.getElementById('grid-container') });精细化设置
lockOffset(进阶)
之前用lockOffset限制了网格内移动,其实可以在拖拽开始时动态计算lockOffset的值。比如在onSortStart里获取容器和拖拽项的尺寸,然后设置lockOffset为不超出容器的范围,这样既能保留网格内的XY移动,又不会越界。不过这个方法需要动态更新组件状态来调整参数,适合对精度要求高的场景。
内容的提问来源于stack exchange,提问作者Farha Naaz
相关产品推荐
相关产品推荐

