You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

react-beautiful-dnd添加DragDropContext提示缺少onDragEnd属性如何解决

报错原因

从你提供的TypeScript类型定义可以看出,DragDropContextProps 接口中仅onDragEnd为不带?修饰的必填属性,其余拖拽生命周期回调均为可选参数。你在使用<DragDropContext>组件时未传入该必填属性,因此触发了类型校验报错。
onDragEnd是react-beautiful-dnd强制要求传入的回调,用于承接拖拽结束后的状态更新逻辑,是整个拖拽功能的核心处理入口。

修复方案
  • 第一步:在TodoList组件内定义onDragEnd回调函数,处理拖拽结束后的列表重排逻辑
  • 第二步:将定义好的onDragEnd函数作为属性传递给<DragDropContext>组件

修改后的完整代码示例:

import type { DropResult, ResponderProvided } from 'react-beautiful-dnd'

export const TodoList: React.FC<TodoListProps> = ({
  todos,
  toggleComplete,
  deleteTodo,
  updateTodo,
  updateTodos // 假设你上层有传入更新整个todos数组的方法,可根据你的实际props调整
}) => {
  const onDragEnd = (result: DropResult, provided: ResponderProvided) => {
    // 拖拽到列表外无效区域,直接终止逻辑
    if (!result.destination) return

    // 重排序todo数组
    const newTodos = Array.from(todos)
    const [draggedTodo] = newTodos.splice(result.source.index, 1)
    newTodos.splice(result.destination.index, 0, draggedTodo)

    // 更新列表状态
    updateTodos(newTodos)
  }

  return (
    <React.Fragment>
    <h2>Current List</h2>
    <DragDropContext onDragEnd={onDragEnd}>
    <ul className = 'list-group'>
      {todos.map((todo, index) => (
        <TodoListItem
          key={todo.text}
          todo={todo}
          toggleComplete={toggleComplete}
          deleteTodo = {deleteTodo}
          updateTodo = {updateTodo}
        />
      ))}
    </ul>
    </DragDropContext>
    </React.Fragment>
  );
};

如果你暂时不需要实现具体的拖拽重排逻辑,也可以先传入空函数占位即可消除报错:

<DragDropContext onDragEnd={() => {}}>

内容的提问来源于stack exchange,提问作者Nicholas Cerillo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 18:24:02