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

react-beautiful-dnd无法实现拖拽功能问题求助

解决react-beautiful-dnd拖拽功能失效问题

问题说明

在React应用中使用react-beautiful-dnd实现列表拖拽,现有包含image、button、TextView的items列表,已配置DragDropContext、Droppable和Draggable组件,但拖拽功能无法正常工作,仅定义了handleDragEnd函数未实现逻辑。

现有代码

import React from "react";
import "./App.css";
import Item from "./Item";
import { DragDropContext, Droppable, Draggable } from "react-beautiful-dnd";
import "react-beautiful-dnd/style.css";

const Center = () => {
  const items = ["image", "button", "TextView"];

  const handleDragEnd = (result) => {
    // TODO: Implement logic for handling the dragged item
  };

  return (
    <div className="Center">
      <DragDropContext onDragEnd={handleDragEnd}>
        <Droppable droppableId="droppable">
          {(provided) => (
            <ul
              className="items"
              {...provided.droppableProps}
              ref={provided.innerRef}
            >
              {items.map((item, index) => (
                <Draggable key={item} draggableId={item} index={index}>
                  {(provided) => (
                    <li
                      className="item"
                      ref={provided.innerRef}
                      {...provided.draggableProps}
                      {...provided.dragHandleProps}
                    >
                      <Item item={item} />
                    </li>
                  )}
                </Draggable>
              ))}
              {provided.placeholder}
            </ul>
          )}
        </Droppable>
      </DragDropContext>
    </div>
  );
};

export default Center;
// Item组件用于渲染列表项内容

修复步骤

1. 将items改为状态变量

当前items是常量,拖拽后无法更新列表顺序,需用useState管理数组状态:

const [items, setItems] = React.useState(["image", "button", "TextView"]);

2. 实现handleDragEnd核心逻辑

拖拽结束后需要重新排序数组并更新状态,补充以下代码:

const handleDragEnd = (result) => {
  // 若拖拽无有效目标,直接返回
  if (!result.destination) return;

  // 复制原数组,避免直接修改状态
  const newItems = [...items];
  // 移除源位置的元素
  const [movedItem] = newItems.splice(result.source.index, 1);
  // 将元素插入目标位置
  newItems.splice(result.destination.index, 0, movedItem);

  // 更新状态,触发组件重新渲染
  setItems(newItems);
};

3. 检查Item组件的事件兼容性

确保Item组件内部没有阻止鼠标事件(如设置pointer-events: none或调用e.preventDefault()),否则会导致拖拽手柄无法响应拖拽操作。

4. 验证key与draggableId的唯一性

当前用item值作为key和draggableId是可行的(三个值唯一),若后续列表出现重复项,需替换为全局唯一ID(如uuid),避免React渲染异常。

内容的提问来源于stack exchange,提问作者internet user

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 05:25:07