React实现拖动元素

安装:pnpm i react-beautiful-dnd @types/react-beautiful-dnd

官网:

https://github.com/atlassian/react-beautiful-dnd

在需要使用拖动的元素最外面使用DragDropContext组件包裹

import {DragDropContext} from 'react-beautiful-dnd'
const onDragEnd = (result: DropResult) => {
  const { source, destination } = result
  if(!destination){
  	return
  }
  if(destination.droppableId === source.droppableId && destination.index === source.index){
  	return
  }
  // TODO 拖动成功后的操作
}


onDragEnd用来拖动元素后的触发操作,destination是null,表示这次拖动没有影响

在具体需要拖动的元素添加:


  {
    (provided) => (
      
      // TODO 放入需要拖动的div
      {provider.placeholder}
      
    )
  }

使用Droppable组件按照上面的来使用,droppableId要保证唯一,Droppable组件内的函数里面渲染的第一个div要添加 ref={provided.innerRef} {...provided.droppableProps},如果是form标签,还需要额外添加:{...provided.draggableProps} {...provided.dragHandleProps}(如果是form标签不是添加droppableProps而是draggableProps)

provider.placeholder用来拖动元素后原来的位置保留之前的元素的位置

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章