四时宝库

程序员的知识宝库

React实现拖动元素(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 拖动成功后的操作
}

<DragDropContext onDragEnd={onDragEnd}>
</DragDropContext>

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

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

<Droppable droppableId="">
  {
    (provided) => (
      <div ref={provided.innerRef} {...provided.droppableProps}>
      // TODO 放入需要拖动的div
      {provider.placeholder}
      </div>
    )
  }
</Droppable>

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

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

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言
    友情链接