我一直在遵循指南添加美丽的dnd到我的react应用程序这里https://www.youtube.com/watch?v=aYZRRyukuIw&t=1s
这是一组练习
const exercises = [
{
title: 'Abdominal Crunch',
id: '4YRrftQysvE1Kz8XACtrq4',
rest: ['30', '30', '30', '30', '30', '', '', '', '', ''],
reps: ['5', '5', '5', '5', '5', '', '', '', '', ''],
time: false
},
{
title: 'Bicep curl',
rest: ['30', '30', '30', '', '', '', '', '', '', ''],
reps: ['5', '5', '', '5', '', '', '', '', '', ''],
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 fieldValue = props.sdk.field.getValue();
const [exercises, setExercises] = useState(fieldValue || []);
您需要访问结果对象来接收项目的初始和最终索引,并相应地重新排序数组:
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, 0, 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, 0, 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
});
};