react-draggable vs react-dnd vs react-zoom-pan-pinch
拖放、可拖動和縮放平移
react-draggablereact-dndreact-zoom-pan-pinch類似套件:

拖放、可拖動和縮放平移

這些庫提供了不同的用戶界面交互功能,允許用戶在網頁應用程序中拖放元素、拖動元素以及縮放和平移內容。react-dnd 是一個功能強大的拖放庫,支持自定義拖放交互,適合需要複雜拖放邏輯的應用。react-draggable 提供簡單的可拖動組件,允許用戶拖動單個元素,適合需要基本拖動功能的應用。react-zoom-pan-pinch 則專注於縮放和平移功能,允許用戶縮放和移動內容,適合需要處理大型畫布或圖像的應用。

npm下載趨勢

3 年

GitHub Stars 排名

統計詳情

套件
下載數
Stars
大小
Issues
發布時間
許可
react-draggable11,162,8639,291453 kB612 個月前MIT
react-dnd6,856,61421,624231 kB473-MIT
react-zoom-pan-pinch4,146,4541,9621.2 MB223 個月前MIT

功能比較: react-draggable vs react-dnd vs react-zoom-pan-pinch

拖放功能

  • react-draggable:

    react-draggable 主要提供單一元素的拖動功能,拖動過程中不涉及拖放區或自定義效果。它的功能相對簡單,適合需要基本拖動的場景。

  • react-dnd:

    react-dnd 提供高度可定制的拖放功能,支持多個拖放區、拖放類型和自定義拖放效果。它允許開發者創建複雜的拖放交互,並提供 API 來管理拖放狀態。

  • react-zoom-pan-pinch:

    react-zoom-pan-pinch 不涉及拖放功能,但提供縮放和平移功能,允許用戶通過手勢或滑鼠操作來移動和縮放內容。

易用性

  • react-draggable:

    react-draggable 非常易於使用,特別是對於簡單的拖動功能。它的 API 直觀,適合快速實現拖動效果。

  • react-dnd:

    react-dnd 需要一定的學習曲線,特別是對於複雜的拖放交互。它的文檔詳細,但配置和實現可能需要更多時間。

  • react-zoom-pan-pinch:

    react-zoom-pan-pinch 的易用性取決於縮放和平移功能的實現。對於需要這些功能的應用來說,它提供了簡單的接口和良好的文檔。

縮放和平移功能

  • react-draggable:

    react-draggable 也不提供縮放或平移功能,僅限於拖動單個元素。

  • react-dnd:

    react-dnd 不提供縮放或平移功能,專注於拖放交互。

  • react-zoom-pan-pinch:

    react-zoom-pan-pinch 專注於縮放和平移,支持多點觸控和滑鼠操作,適合需要處理大範圍內容的應用。

代碼示例

  • react-draggable:

    拖動示例

    import Draggable from 'react-draggable';
    
    const DraggableComponent = () => {
      return (
        <Draggable>
          <div style={{ width: '100px', height: '100px', background: 'lightcoral' }}>拖動我</div>
        </Draggable>
      );
    };
    
    export default DraggableComponent;
    
  • react-dnd:

    拖放示例

    import { DndProvider, useDrag, useDrop } from 'react-dnd';
    import { HTML5Backend } from 'react-dnd-html5-backend';
    
    const ItemType = 'BOX';
    
    const DraggableBox = () => {
      const [{ isDragging }, drag] = useDrag({
        type: ItemType,
        item: { id: 1 },
        collect: (monitor) => ({ isDragging: monitor.isDragging() }),
      });
    
      return <div ref={drag} style={{ opacity: isDragging ? 0.5 : 1 }}>拖動我</div>;
    };
    
    const DropZone = () => {
      const [{ isOver }, drop] = useDrop({
        accept: ItemType,
        drop: (item) => console.log(`Dropped item: ${item.id}`),
        collect: (monitor) => ({ isOver: monitor.isOver() }),
      });
    
      return <div ref={drop} style={{ background: isOver ? 'lightblue' : 'lightgray', height: '200px' }}>放置區域</div>;
    };
    
    const App = () => (
      <DndProvider backend={HTML5Backend}>
        <DraggableBox />
        <DropZone />
      </DndProvider>
    );
    
    export default App;
    
  • react-zoom-pan-pinch:

    縮放和平移示例

    import { TransformWrapper, TransformComponent } from 'react-zoom-pan-pinch';
    
    const ZoomPanComponent = () => {
      return (
        <TransformWrapper>
          <TransformComponent>
            <img src='your-image.jpg' alt='可縮放的內容' />
          </TransformComponent>
        </TransformWrapper>
      );
    };
    
    export default ZoomPanComponent;
    

如何選擇: react-draggable vs react-dnd vs react-zoom-pan-pinch

  • react-draggable:

    如果您只需要為單個元素添加簡單的拖動功能,請選擇 react-draggable。它易於使用,並且不需要大量配置,適合需要快速實現拖動功能的項目。

  • react-dnd:

    如果您需要實現複雜的拖放功能,例如支持多個拖放區、可自定義的拖放效果和狀態管理,請選擇 react-dnd。它提供了高度的靈活性和可擴展性,適合需要精細控制拖放行為的應用。

  • react-zoom-pan-pinch:

    如果您的應用需要縮放和平移功能,例如在地圖或圖像畫布上,請選擇 react-zoom-pan-pinch。它提供了對縮放和移動的良好支持,適合需要處理大範圍內容的應用。

react-draggable 的 README

React-Draggable

CI npm version npm downloads gzip size

A simple component for making elements draggable.

[Demo | Changelog]

<Draggable>
  <div>I can now be moved around!</div>
</Draggable>

Table of Contents

Installation

npm install react-draggable
# or
yarn add react-draggable
// ES Modules
import Draggable from 'react-draggable';
import { DraggableCore } from 'react-draggable';

// CommonJS
const Draggable = require('react-draggable');
const { DraggableCore } = require('react-draggable');

TypeScript types are included.

Compatibility

VersionReact Version
4.x16.3+
3.x15 - 16
2.x0.14 - 15

Quick Start

import React, { useRef } from 'react';
import Draggable from 'react-draggable';

function App() {
  const nodeRef = useRef(null);

  return (
    <Draggable nodeRef={nodeRef}>
      <div ref={nodeRef}>Drag me!</div>
    </Draggable>
  );
}

View the Demo and its source for more examples.

API

<Draggable>

A <Draggable> element wraps an existing element and extends it with new event handlers and styles. It does not create a wrapper element in the DOM.

Draggable items are moved using CSS Transforms. This allows items to be dragged regardless of their current positioning (relative, absolute, or static). Elements can also be moved between drags without incident.

If the item you are dragging already has a CSS Transform applied, it will be overwritten by <Draggable>. Use an intermediate wrapper (<Draggable><span>...</span></Draggable>) in this case.

Props

type DraggableEventHandler = (e: Event, data: DraggableData) => void | false;

type DraggableData = {
  node: HTMLElement,
  x: number, y: number,
  deltaX: number, deltaY: number,
  lastX: number, lastY: number,
};
PropTypeDefaultDescription
allowAnyClickbooleanfalseAllow dragging on non-left-button clicks
allowMobileScrollbooleanfalseDon't prevent touchstart, allowing scrolling inside containers
axis'both' | 'x' | 'y' | 'none''both'Axis to allow dragging on
boundsobject | string-Restrict movement. Use 'parent', a CSS selector, or {left, top, right, bottom}
cancelstring-CSS selector for elements that should not initiate drag
defaultClassNamestring'react-draggable'Class name applied to the element
defaultClassNameDraggingstring'react-draggable-dragging'Class name applied while dragging
defaultClassNameDraggedstring'react-draggable-dragged'Class name applied after drag
defaultPosition{x: number, y: number}{x: 0, y: 0}Starting position
disabledbooleanfalseDisable dragging
enableUserSelectHackbooleantrueAdd user-select: none while dragging
grid[number, number]-Snap to grid [x, y]
handlestring-CSS selector for the drag handle
nodeRefReact.RefObject-Ref to the DOM element. Required for React Strict Mode
noncestring-CSP nonce for the injected user-select <style> element (see Content Security Policy)
offsetParentHTMLElement-Custom offsetParent for drag calculations
onDragDraggableEventHandler-Called while dragging
onMouseDown(e: MouseEvent) => void-Called on mouse down
onStartDraggableEventHandler-Called when dragging starts. Return false to cancel
onStopDraggableEventHandler-Called when dragging stops
position{x: number, y: number}-Controlled position
positionOffset{x: number | string, y: number | string}-Position offset (supports percentages)
scalenumber1Scale factor for dragging inside transformed parents

Note: Setting className, style, or transform on <Draggable> will error. Set them on the child element.

<DraggableCore>

For users that require full control, <DraggableCore> provides drag callbacks without managing state or styles. It does not set any transforms; you must handle positioning yourself.

See React-Resizable and React-Grid-Layout for usage examples.

Props

<DraggableCore> accepts a subset of <Draggable> props:

  • allowAnyClick
  • allowMobileScroll
  • cancel
  • disabled
  • enableUserSelectHack
  • grid
  • handle
  • nodeRef
  • offsetParent
  • onDrag
  • onMouseDown
  • onStart
  • onStop
  • scale

Using nodeRef

To avoid ReactDOM.findDOMNode() deprecation warnings in React Strict Mode, pass a nodeRef prop:

function App() {
  const nodeRef = useRef(null);

  return (
    <Draggable nodeRef={nodeRef}>
      <div ref={nodeRef}>Drag me!</div>
    </Draggable>
  );
}

For custom components, forward both the ref and props:

const MyComponent = forwardRef((props, ref) => (
  <div {...props} ref={ref}>Draggable content</div>
));

function App() {
  const nodeRef = useRef(null);

  return (
    <Draggable nodeRef={nodeRef}>
      <MyComponent ref={nodeRef} />
    </Draggable>
  );
}

Controlled vs. Uncontrolled

<Draggable> is a 'batteries-included' component that manages its own state. For complete control, use <DraggableCore>.

For programmatic repositioning while using <Draggable>'s state management, pass the position prop:

function ControlledDraggable() {
  const nodeRef = useRef(null);
  const [position, setPosition] = useState({ x: 0, y: 0 });

  const handleDrag = (e, data) => {
    setPosition({ x: data.x, y: data.y });
  };

  const resetPosition = () => setPosition({ x: 0, y: 0 });

  return (
    <>
      <button onClick={resetPosition}>Reset</button>
      <Draggable nodeRef={nodeRef} position={position} onDrag={handleDrag}>
        <div ref={nodeRef}>Drag me or reset!</div>
      </Draggable>
    </>
  );
}

Content Security Policy

To prevent text from being highlighted while dragging, react-draggable injects a small <style> element into the document <head> the first time a drag starts (the enableUserSelectHack, on by default). Under a strict Content Security Policy that omits 'unsafe-inline' from style-src, the browser blocks that element and logs a CSP violation.

You have three ways to handle this:

  1. Pass a nonce. Provide the same nonce your CSP header advertises and it's applied to the injected element:

    <Draggable nonce={cspNonce}>
      <div>Drag me</div>
    </Draggable>
    
  2. Do nothing, if you use webpack. When no nonce prop is given, react-draggable falls back to webpack's __webpack_nonce__ global if your build defines it — no per-component prop needed.

  3. Opt out of the injected style. Set enableUserSelectHack={false} and add the two rules to your own (CSP-compliant) stylesheet:

    .react-draggable-transparent-selection *::-moz-selection { all: inherit; }
    .react-draggable-transparent-selection *::selection { all: inherit; }
    

The nonce is only read when the element is first created. The same element is shared by every <Draggable>/<DraggableCore> on the page, so set the nonce on whichever instance drags first (or, more simply, set it consistently everywhere).

Contributing

  • Fork the project
  • Run yarn dev to start the development server
  • Make changes and add tests
  • Run yarn test to ensure tests pass
  • Submit a PR

Release Checklist

  1. Update CHANGELOG.md
  2. Run make release-patch, make release-minor, or make release-major
  3. Run make publish

License

MIT