如何在react-beautiful-dnd拖拽时保留源列表项不隐藏?
实现react-beautiful-dnd拖拽时源列表项不消失的方案
1. 覆盖默认拖拽样式,让源项一直显示
react-beautiful-dnd默认会给拖拽中的源项加rfd__dragging(旧版本是react-beautiful-dnd-dragging)类,把它隐藏起来。你可以在CSS里覆盖这个样式,强制源项始终可见:
/* 适配新版react-beautiful-dnd */ .rfd__dragging { opacity: 1 !important; visibility: visible !important; position: relative !important; } /* 如果用的是旧版本组件,用这个选择器 */ .react-beautiful-dnd-dragging { opacity: 1 !important; visibility: visible !important; position: relative !important; }
2. 修改拖拽结束逻辑,只更新目标列表
在onDragEnd回调里,只把拖拽项添加到列表B,千万别修改列表A的数据:
const handleDragEnd = (result) => { const { source, destination, draggableId } = result; // 没有有效目标位置就直接返回 if (!destination) return; // 如果是在同一列表里拖拽,不用处理(要是不需要A列表排序就保留这个判断) if (source.droppableId === destination.droppableId) return; // 从列表A里找到对应的拖拽项 const draggedItem = listA.find(item => item.id === draggableId); if (!draggedItem) return; // 把拖拽项插入到列表B的指定位置,记得深拷贝避免引用问题 const updatedListB = Array.from(listB); updatedListB.splice(destination.index, 0, { ...draggedItem }); setListB(updatedListB); // 重点:这里绝对不能修改listA的状态 };
3. 确保Draggable组件配置正确
给列表A的每个Draggable组件设置唯一的draggableId,正常包裹子元素就行:
<Droppable droppableId="listA"> {(provided) => ( <div {...provided.droppableProps} ref={provided.innerRef} > {listA.map((item, index) => ( <Draggable key={item.id} draggableId={item.id} index={index}> {(provided, snapshot) => ( <div ref={provided.innerRef} {...provided.draggableProps} {...provided.dragHandleProps} className={`item ${snapshot.isDragging ? 'dragging-item' : ''}`} > {item.content} </div> )} </Draggable> ))} {provided.placeholder} </div> )} </Droppable>
这么设置之后,拖拽列表A的项到B的时候,A里的对应项会一直显示,同时B会新增这个拖拽项,完全符合你的要求。
内容的提问来源于stack exchange,提问作者Profer
相关产品推荐
相关产品推荐

