行业知识
react-beautiful-dnd组件报Unable to find draggable with id
2026-11-05 15:23:43
来源:互联网转载
一、问题现象
项���中使用react-beautiful-dnd组件实现可拖拽,但拖了1次后可能会出现拖拽异常(元素拖不动),打开控制台会发现有报错
二、解决方案
给Draggable组件和其下方的p添加了key就正常了,以下是我自己简单写的一个demo,可供参考
import { useState } from 'react'import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';import './App.css'const mocklist = [ { label: 'item11', id:'aa', value: 'aa', color: 'red' }, { label: 'item22', value: 'bb', id:'bb', color: 'blue' }, { label: 'item33', value: 'cc', id:'cc', color: 'yellow' }, { label: 'item44', value: 'dd', id:'dd', color: 'pink' }, { label: 'item55', value: 'ee', id:'ee', color:'green' },]function App() { const [list,setList] =useState(mocklist); // 重新排序-更新列表 const reorder = (list, startIndex, endIndex) => { const result = [...list]; const [removed] = result.splice(startIndex, 1); result.splice(endIndex, 0, removed); return result; }; // 拖拽结束 const onDragEnd =(result)=>{ if (!result.destination) { return; } if (result.destination.index === result.source.index) { return; } const newList = reorder( list, result.source.index, result.destination.index, ); setList(newList) } return ( onDragEnd} {provided => ( provided.innerRef} {...provided.droppableProps} { list.map((item, index) => { return ( item.id} index={index} key={item.id} {provided => ( provided.innerRef} key={item.value} {...provided.draggableProps} {...provided.dragHandleProps} { marginBottom: 10,backgroundColor:item.color }} {item.label} )} ); }) } {provided.placeholder} )} )}export default App 三、备注
注意:貌似这个组件在vite脚手架起的项目中会有问题(元素不能被拖拽),亲测在react脚手架ok