前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >React drag 排序折腾小记

React drag 排序折腾小记

作者头像
jgrass
发布2024-12-25 18:11:43
发布2024-12-25 18:11:43
910
举报
文章被收录于专栏:蔻丁杂记蔻丁杂记

需求,一个列表,期望可以支持拖动排序。

折腾过程

react-beautiful-dnd

首页相遇的是 atlassian/react-beautiful-dnd,但是这个库已经进入维护状态,基本不更新了,在 React 18 严格默认下使用,会有问题。

hello-pangea/dnd

好消息是后继有人 hello-pangea/dnd: Beautiful and accessible drag and drop for lists with React.

dnd 是基于前者的,所以 API 完全通用,找到的 react-beautiful-dnd 资料对其也适用。

基本用法:

Using React Beautiful DnD to Implement Drag and Drop

Simple Drag and Drop List in React JS

至此能够解决基本问题。

但是,

有一个需求无法被满足,就是列表换行的场景。

2018 年有人提出这个问题,但是没有处理,最后还在 issue 中骂了起来,翻译成中文就是:“No BB, you can you up.” 😂

Support lists with wrapping rows (Grid layout) · Issue #316 · atlassian/react-beautiful-dnd

dnd kit

新发现:dnd kit – a modern drag and drop toolkit for React

这个库可以支持换行下的拖动排序,基本用法:

React Drag And Drop List With dnd Kit (React Drag and Drop Tutorial) - YouTube

Demo

coopercodes/ReactDndKitList: From the video React Drag And Drop List With dnd Kit (React Drag and Drop Tutorial)

但是,(哎,又有但是),有一个小问题,和一个大问题

小问题是,如果每个 Item 的长度是不一样的,则拖动时,会进行缩放,看起来有点点奇怪

大问题是,如果 Item 中有需要进行交互的内容,则会失效,

How do I prevent draggable on input and btns · Issue #477 · clauderic/dnd-kit

Question: Respond to a click on the dragable item · Issue #591 · clauderic/dnd-kit

当然,有解决办法,需要对 sensor 做一些自定义的处理。

最终方案

综合看下来,最好的方案是这个:

https://codesandbox.io/s/patient-dew-4655gf

same with: @dnd-kit/sortable starter template - CodeSandbox

解决了不同长度的 Item 在拖动时的预览缩放问题,

通过使用控制点的方式(仅在部分 UI 上响应拖动操作),解决了 Item 内部不可交互的问题。

上面的代码基本可以直接拿来用,改改样式就可以了,Perfect~

具体实现效果,可以看扩展管理工具:https://chromewebstore.google.com/detail/extension-manager/efajbgpnlnobnkgdcgcnclngeolnmggp

原文链接: https://cloud.tencent.com/developer/article/2481563

本作品采用 「署名 4.0 国际」 许可协议进行许可,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2023年9月14日 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 折腾过程
    • react-beautiful-dnd
    • hello-pangea/dnd
    • dnd kit
  • 最终方案
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档