Skip to content

Latest commit

 

History

History
103 lines (92 loc) · 2.72 KB

README.md

File metadata and controls

103 lines (92 loc) · 2.72 KB

react-useDraggable-hook

npm license

用于使 DOM 元素可跟随鼠标拖拽位移的 React Hook。
A React Hook for making DOM elements translate with dragging.

Usage

import useDraggable from 'use-draggable-hook'

function App() {
  const { target } = useDraggable<HTMLDivElement>()

  return (
    <div className="App">
      <div className="test-element" ref={target}>
        Draggable element
      </div>
    </div>
  )
}

Try it on Codesandbox: [Simple example] [Advanced example].

Interface & Options

export type UseDraggable = <T extends HTMLElement>(
  options?: DraggableOptions
) => {
  /** target element ref  */
  target: React.RefObject<T>
  /** position state [x, y] */
  position: [number, number]
  /** function to set a new position value. */
  setPosition: (position: [number, number], transition?: string) => void
}
export interface DraggableOptions {
  /** use Event.preventDefault with the touchmove events */
  prevent?: boolean
  /** listen touch events */
  touch?: boolean
  /** listen mouse events */
  mouse?: boolean
  /** dragging direction */
  direction?: 'vertical' | 'horizontal' | 'both'
  /** set css transform */
  setCSS?: boolean
  /** max dragging distance */
  maxDistance?: {
    x?: { max?: number; min?: number }
    y?: { max?: number; min?: number }
  }
  /** position step size */
  stepSize?:
    | number
    | {
        x: number
        y: number
      }
  /** start callback */
  onStart?: (
    target: React.RefObject<HTMLElement>,
    position: [number, number],
    setPosition: (position: [number, number], transition?: string) => void
  ) => void
  /** move callback */
  onMove?: (
    target: React.RefObject<HTMLElement>,
    position: [number, number],
    setPosition: (position: [number, number], transition?: string) => void
  ) => void
  /** end callback */
  onEnd?: (
    target: React.RefObject<HTMLElement>,
    position: [number, number],
    setPosition: (position: [number, number], transition?: string) => void
  ) => void
}

const defaultOptions = {
  prevent: true,
  touch: true,
  mouse: true,
  direction: 'both',
  maxDistance: {
    x: { max: Infinity, min: -Infinity },
    y: { max: Infinity, min: -Infinity },
  },
  stepSize: 0,
  setCSS: true,
  onStart: function () {},
  onMove: function () {},
  onEnd: function () {},
}