问题描述
我一直在按照指南为我的 React 应用添加漂亮的 dnd https://www.youtube.com/watch?v=aYZRRyukuIw&t=1s
这是一组练习
canvas.DrawCircle
我正在通过练习绘制地图
const exercises = [
{
title: 'Abdominal Crunch',id: '4YRrftQysve1Kz8XACtrq4',rest: ['30','30','',''],reps: ['5','5',time: false
},{
title: 'Bicep curl',time: false
}
];
这运行良好,但我遇到的问题是保存状态 ...
return (
<section>
<div>
<DragDropContext onDragEnd={(result) => console.log(result)}>
<Droppable droppableId="items">
{(provided,snapshot) => {
return (
<div
className="exercises"
{...provided.droppableProps}
ref={provided.innerRef}
>
{exercises.map((exercise,index) => {
return (
<Draggable
key={exercise.id}
draggableId={exercise.id}
index={index}
>
{(provided,snapshot) => {
return (
<div
className="exercise__item"
{...provided.draggableProps}
{...provided.dragHandleProps}
å
ref={provided.innerRef}
style={{
userSelect: "none",...provided.draggableProps.style,}}
>
{exercise}
</div>
);
}}
</Draggable>
);
})}
{provided.placeholder}
</div>
);
}}
</Droppable>
</DragDropContext>
</div>
</section>
);
};
export default ExercisesList;
。
onDragEnd
使用我已经配置的现有状态?
const onDragEnd = (result) => {
if(!result.destination) return;
// Can I save the state in here?
}
解决方法
您需要访问结果对象以接收项目的初始和最终索引并相应地对数组重新排序:
const onDragEnd = (result) => {
if(!result.destination) return;
setExercises(prevExercises => {
const exercises = Array.from(prevExercises); // Create a new array to not mutate the previous one
const [removed] = exercises.splice(result.source.index,1); // Removes the drag item from the array by using the start index
exercises.splice(result.destination.index,removed); // Inserts the moved item at its new position using the end index
return exercises // Returns the reordered array to the hook to be saved
})
}
我更新了名字,@david-riches
, const onDragEnd = (result) => {
if (!result.destination) return;
const { source,destination } = result;
setExercises((prevExercises) => {
const result = Array.from(prevExercises); // Create a new array to not mutate the previous one
const [removed] = result.splice(source.index,1); // Removes the drag item from the array by using the start index
result.splice(destination.index,removed); // Inserts the moved item at its new position using the end index
return result; // Returns the reordered array to the hook to be saved
});
};