React drag 排序折騰小記

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

折騰過程

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://www.cnblogs.com/jasongrass/p/17703227.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章