一、问题现象
项目中使用react-beautiful-dnd组件实现可拖拽,但拖了1次后可能会出现拖拽异常(元素拖不动),打开控制台会发现有报错
二、解决方案
给Draggable组件和其下方的div添加了key就正常了,以下是我自己简单写的一个demo,可供参考
import { useState } from 'react'
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';
import './App.css'const mocklist = [{label: 'item11',id:'aa',value: 'aa',color: 'red'},{label: 'item22',value: 'bb',id:'bb',color: 'blue'},{label: 'item33',value: 'cc',id:'cc',color: 'yellow'},{label: 'item44',value: 'dd',id:'dd',color: 'pink'},{label: 'item55',value: 'ee',id:'ee',color:'green'},
]
function App() {const [list,setList] =useState(mocklist);// 重新排序-更新列表const reorder = (list, startIndex, endIndex) => {const result = [...list];const [removed] = result.splice(startIndex, 1);result.splice(endIndex, 0, removed);return result;};// 拖拽结束const onDragEnd =(result)=>{if (!result.destination) {return;}if (result.destination.index === result.source.index) {return;}const newList = reorder(list,result.source.index,result.destination.index,);setList(newList)}return (<div><DragDropContext onDragEnd={onDragEnd}><div><Droppable droppableId="list" key="list">{provided => (<div ref={provided.innerRef} {...provided.droppableProps}>{list.map((item, index) => {return (<Draggable draggableId={item.id} index={index} key={item.id}>{provided => (<divref={provided.innerRef}key={item.value}{...provided.draggableProps}{...provided.dragHandleProps}><div style={{ marginBottom: 10,backgroundColor:item.color }}>{item.label}</div></div>)}</Draggable>);})}{provided.placeholder}</div>)}</Droppable></div></DragDropContext></div>)
}export default App
三、备注
注意:貌似这个组件在vite脚手架起的项目中会有问题(元素不能被拖拽),亲测在react脚手架ok