我正在开发一个待办事项列表应用程序,我想让待办事项可拖动。 我正在使用 dnd-kit 来实现相同的目的。
我在父容器中提供了 DndContext 和 SortableContext。 ListContainer.jsx
<DndContext collisionDetection={closestCorners}>
<SortableContext
items={toDo}
strategy={verticalListSortingStrategy}
>
<div className="bg-red-900">
{toDo.map((item) => (
<ToDo
key={item._id}
id={item._id}
value={text}
isCompleted={item.completed}
text={item.text}
updateTodo={() => updateTodo(item._id, item.text)}
deleteTodo={() => deleteToDo(user.id, item._id, setToDo)}
updateState={() => updateState(item._id)}
inputRef={inputRef}
/>
))}
</div>
</SortableContext>
</DndContext>
然后我使用 useSortable 钩子来解构一些使待办事项可拖动所需的属性。
Todo.jsx
return (
<div
ref={setNodeRef}
{...listeners}
{...attributes}
style={style}
className={`${
isDark
? "bg-black/20 text-white hover:bg-black/60"
: "bg-gray-50/80 hover:bg-gray-200"
} w-full md:w-[70%] mx-auto my-2 flex items-center font-[600] font-mono text-lg justify-between rounded-md shadow-md transition-colors`}
>
<div
className="flex flex-grow items-center h-full p-4 gap-3 cursor-pointer"
onClick={handleCheckboxChange}
>
<input
type="checkbox"
checked={isChecked}
className="cursor-pointer"
readOnly
/>
<div className={`${isChecked ? "line-through" : ""} select-none`}>
<p> {text} </p>
</div>
</div>
<div className="flex gap-4 px-4 select-none text-lg">
<button onClick={handleUpdateToDo}>
<BiEdit />
</button>
<button onClick={deleteToDoHandler}>
<RiDeleteBin6Line />
</button>
</div>
</div>
);
};
我的待办事项组件上有多个侦听器会导致侦听器冲突。
我尝试使用拖动处理程序,但我的待办事项仍然不会移动。
return (
<div
ref={setNodeRef}
style={style}
className={`${
isDark
? "bg-black/20 text-white hover:bg-black/60"
: "bg-gray-50/80 hover:bg-gray-200"
} w-full md:w-[70%] mx-auto my-2 flex items-center font-[600] font-mono text-lg justify-between rounded-md shadow-md transition-colors`}
>
<div
className="flex flex-grow items-center h-full p-4 gap-3 cursor-pointer"
onClick={handleCheckboxChange}
>
<input
type="checkbox"
checked={isChecked}
className="cursor-pointer"
readOnly
/>
<div className={`${isChecked ? "line-through" : ""} select-none`}>
<p> {text} </p>
</div>
</div>
<div className="flex gap-4 px-4 select-none text-lg">
<button onClick={handleUpdateToDo}>
<BiEdit />
</button>
<button onClick={deleteToDoHandler}>
<RiDeleteBin6Line />
</button>
<button className="px-2 py-2" {...attributes} {...listeners}>
Drag me
</button>
</div>
</div>
);
我在这里缺少什么?
您必须在
useSortable
组件中使用 ToDo
钩子,只需确保传递给该钩子的 id
是唯一的。这可能就是问题所在。
但您需要设置 {...attributes}
和 {...listeners}