33k Stars 知名前端庫停止維護,npm 包已棄用!
近期,知名 React 拖拽庫 react-beautiful-dnd 宣布了項目棄用的決定,未來將不再維護。這一決定源于其存在的缺陷與局限性,促使作者轉向開發一個更加現代化的拖拽解決方案——Pragmatic drag and drop(下面會介紹),其旨在提供更佳的性能、靈活性和可訪問性。
作為 React 生態中不可或缺的工具庫,react-beautiful-dnd 曾以其卓越的拖放體驗贏得了廣泛贊譽,其 npm 周下載量高達 163 萬次。
對于仍希望繼續使用 react-beautiful-dnd 的開發者,以下是一些可行的選擇:
- fork 與修補:可以fork react-beautiful-dnd 項目以繼續使用它,或者利用patch-package進行定制修補。
- 遷移至 fork 版本:考慮遷移到react-beautiful-dnd的某個活躍 fork 版本,以繼續享受其功能。
- 探索其他解決方案:考慮遷移到如 dnd-kit 等其他類似的拖拽解決方案。
- 轉向 Pragmatic drag and drop:為了獲得更快速、更現代化的體驗,可以手動遷移到Pragmatic drag and drop,或者利用官方提供的遷移包進行自動遷移。
下面來看看前端還有哪些好用的拖拽庫。
Vue
VueDraggablePlus
VueDraggablePlus 是一個支持 Vue2 和 Vue3 的拖拽庫,尤雨溪都在推薦:
Sortablejs 是一個非常流行的拖拽庫,不過這個庫的 Vue 3 版本已經三年沒更新了,可以說是已經跟 Vue 3 嚴重脫節,所以就誕生了 VueDraggablePlus,這個組件就是基于 Sortablejs 實現的。
Github:https://github.com/Alfred-Skyblue/vue-draggable-plus。
React
dnd-kit
dnd-kit 是一個專為 React 設計的現代化、輕量級、高性能且易于訪問的拖拽解決方案,其 npm 周下載量 200 萬左右。
import React, {useState} from 'react';
import {DndContext} from '@dnd-kit/core';
import {Draggable} from './Draggable';
import {Droppable} from './Droppable';
function Example() {
const [parent, setParent] = useState(null);
const draggable = (
<Draggable id="draggable">
Go ahead, drag me.
</Draggable>
);
return (
<DndContext onDragEnd={handleDragEnd}>
{!parent ? draggable : null}
<Droppable id="droppable">
{parent === "droppable" ? draggable : 'Drop here'}
</Droppable>
</DndContext>
);
function handleDragEnd({over}) {
setParent(over ? over.id : null);
}
}
Github:https://github.com/clauderic/dnd-kit。
react-dnd
react-dnd 是一個由 React 和 Redux 的核心作者 Dan Abramov 開發的強大的庫,旨在幫助開發者輕松構建復雜的拖拽界面,其 npm 周下載量 200 萬左右。
import React from 'react'
import { useDrag } from 'react-dnd'
import { ItemTypes } from './Constants'
export default function Card({ isDragging, text }) {
const [{ opacity }, dragRef] = useDrag(
() => ({
type: ItemTypes.CARD,
item: { text },
collect: (monitor) => ({
opacity: monitor.isDragging() ? 0.5 : 1
})
}),
[]
)
return (
<div ref={dragRef} style={{ opacity }}>
{text}
</div>
)
}
Github:https://github.com/react-dnd/react-dnd。
通用
pragmatic-drag-and-drop
pragmatic-drag-and-drop 是 react-beautiful-dnd 作者開發的新拖拽庫。它是一個較底層的拖拽工具鏈,它使得開發者能夠安全且成功地利用瀏覽器內置的拖拽功能。這個工具鏈不依賴于特定的視圖層,因此可以與 React、Svelte、Vue、Angular 等多種前端框架無縫集成。一些大型產品,如Jira、Confluence,都在使用 Pragmatic Drag and Drop 來實現拖拽功能。
Github:https://github.com/atlassian/pragmatic-drag-and-drop。
Swapy
Swapy 是一個全新的拖拽庫,僅發布三個月,就在 GitHub 上收獲了 6k+ Stars,并且還在快速增長中。Swapy 與框架無關,只需幾行代碼就可以將任何布局轉換為可拖動交換的布局。
Github:https://github.com/TahaSh/swapy。