解决 “Unable to find draggable element with id” 错误的方法
⭐️最近在使用 "react-beautiful-dnd"
拖拽库时,遇到 "Unable to find draggable element with id"
错误。
🚀 这个错误表示拖拽库无法找到与指定的 draggableId
匹配的可拖拽元素。本篇博客将解释该错误的常见原因以及如何解决它。(最后有彩蛋🌈)
错误提示如下👇
问题描述
"Unable to find draggable element with id"
错误通常发生在以下情况:
- 当你拖拽一个元素时,拖拽库无法找到匹配
draggableId
的可拖拽元素。 - 这个错误可能会在控制台中显示,通常伴随着一些堆栈跟踪信息,但通常没有足够的信息来迅速定位问题。
常见原因
以下是可能导致 "Unable to find draggable element with id"
错误的常见原因:
-
拼写错误:
draggableId
的值拼写错误或包含额外的空格,与实际的可拖拽元素的ID
不匹配。 -
未正确包装元素: 没有正确使用
Draggable
组件来包装可拖拽的元素,或者没有为draggableId
提供正确的值。 -
数据同步问题: 如果你的拖拽元素是从后端数据动态渲染的,可能需要确保数据的同步性。如果数据在渲染之前被改变,可能导致无法找到匹配的
draggableId
。 -
其他错误: 其他与拖拽相关的错误,如逻辑错误,也可能导致这个问题。
🌰下面是我的数据结构
const initialData = [
{
id: 'column1',
title: 'Column 1',
tasks: [
{ id: 'task1', content: 'Task 1' },
{ id: 'task2', content: 'Task 2' },
{ id: 'task3', content: 'Task 3' },
],
},
{
id: 'column2',
title: 'Column 2',
tasks: [
{ id: 'task4', content: 'Task 4' },
{ id: 'task5', content: 'Task 5' },
],
},
];
-
在这个案例中,
draggableId
的值与数据结构中的对象的id
属性一致,确保了匹配。这是因为 “react-beautiful-dnd” 需要正确的draggableId
来识别要拖拽的元素。 -
所以,如果你想要拖拽
task 1
元素,你的draggableId
应该是task1
,以与数据结构中的 id 属性匹配。如果你希望拖拽Column 1
列,你的draggableId
应该是column1
以匹配数据结构中的列的 id 属性。 -
确保在设置
draggableId
时使用正确的值,以匹配要拖拽的元素在数据结构中的唯一标识符。如果你在设置draggableId
时出现错误,可能会导致"Unable to find draggable element with id"
错误。
代码示例
🌰以下是一个示例代码,演示了如何使用 "react-beautiful-dnd"
来设置可拖拽元素和容器:
import React from 'react';
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';
// 使用数组代表列,每个列中包含一个任务数组
const initialData = [
{
id: 'column1',
title: 'Column 1',
tasks: [
{ id: 'task1', content: 'Task 1' },
{ id: 'task2', content: 'Task 2' },
{ id: 'task3', content: 'Task 3' },
],
},
{
id: 'column2',
title: 'Column 2',
tasks: [
{ id: 'task4', content: 'Task 4' },
{ id: 'task5', content: 'Task 5' },
],
},
};
function App() {
const onDragEnd = (result) => {
// 在拖放结束时的处理逻辑
};
return (
<DragDropContext onDragEnd={onDragEnd}>
<Droppable droppableId="outer-container" direction="horizontal" type="column">
{(provided) => (
<div
ref={provided.innerRef}
{...provided.droppableProps}
>
{initialData.map((column, index) => (
<Draggable draggableId={column.id} index={index} key={column.id}>
{(provided) => (
<div
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
>
<Droppable droppableId={column.id} type="task">
{(provided) => (
<div
ref={provided.innerRef}
{...provided.droppableProps}
>
{column.tasks.map((task, taskIndex) => (
<Draggable draggableId={task.id} index={taskIndex} key={task.id}>
{(provided, snapshot) => (
<div
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
>
{task.content}
</div>
)}
</Draggable>
))}
</div>
)}
</Droppable>
</div>
)}
</Draggable>
))}
</div>
)}
</Droppable>
</DragDropContext>
);
}
export default App;