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

React DnD Kit拖拽正常但放置后图片复位问题求助

问题分析与解决方案

拖拽后图片回到原位的核心问题有两个:

  1. SortableContext的items参数错误
    SortableContext需要接收的是可排序项的ID数组,而非完整的图片对象数组。你当前直接传入photos(对象数组),导致DnD Kit无法正确识别排序项的标识。

  2. 索引获取逻辑错误
    使用items.indexOf(active.id)在对象数组中无法找到对应元素——indexOf匹配的是元素本身,而非对象的id属性,因此始终返回-1,数组不会被修改。


修改后的代码片段

PhotoGallery.jsx

import { useEffect, useState } from "react";
import { fetchPexelsImages } from "./PexelsService";
import { DndContext, closestCenter } from "@dnd-kit/core";
import {
  arrayMove,
  SortableContext,
  rectSwappingStrategy,
} from "@dnd-kit/sortable";
import SortablePhoto from "./SortablePhoto";

function PhotoGallery({ photos, setPhotos }) {
  const handleDragEnd = (event) => {
    const { active, over } = event;

    if (active.id === over.id) {
      return;
    }
    
    setPhotos((items) => {
      // 用findIndex匹配对象id获取正确索引
      const activeIndex = items.findIndex(item => item.id === active.id);
      const overIndex = items.findIndex(item => item.id === over.id);
      
      // 确保索引有效再执行移动
      if (activeIndex === -1 || overIndex === -1) return items;
      
      return arrayMove(items, activeIndex, overIndex);
    });
  };

  return (
    <div className="container mx-auto my-4">
      <h1 className="text-2xl font-semibold mb-4">Photo Gallery</h1>
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        <DndContext
          collisionDetection={closestCenter}
          onDragEnd={handleDragEnd}
        >
          {/* 传入id数组而非对象数组 */}
          <SortableContext items={photos.map(photo => photo.id)} strategy={rectSwappingStrategy}>
            {photos.map((photo) => (
              <SortablePhoto key={photo.id} photo={photo} />
            ))}
          </SortableContext>
        </DndContext>
      </div>
    </div>
  );
};

export default PhotoGallery;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 06:06:00