我正在使用 React.js 中的拖放交互。我正在使用拼接函数对一个 "行 "数组进行重新排序,当拖动完成后,会使用下面的 onDragEnd 函数调用该函数。
onDragEnd = (result) => {
const { destination, source, draggableId, type } = result;
if (!destination) {
return;
}
if (
destination.draggableId === source.droppableId &&
destination.index === source.index
) {
return;
}
if (type === "row") {
const newRowOrder = Array.from(**this.state.currentRows**);
newRowOrder.splice(source.index, 1);
newRowOrder.splice(destination.index, 0, **draggableId**);
const newState = {
...this.state,
currentRows: newRowOrder,
};
this.setState(newState);
}
};
在调用onDragEnd函数之前,currentRow的状态是这样的。在调用onDragEnd函数之前,currentRow的状态是这样的:
调用该函数时,拼接函数起作用(我想),但它并没有移动数组中的整个对象,只是移动了ID。拼接函数中使用的dragableId是需要移动的对象的ID。
在调用onDragEnd函数后,currentRow的状态是这样的。调用onDragEnd函数后的currentRow状态是这样的:
能否将整个对象移动到一个新的索引中?
我认为你只是插入了可拖动的Id值。newRowOrder.splice(destination.index, 0, **draggableId**);
你可以用 Array.find
函数并插入整个对象
onDragEnd = (result) => {
const { destination, source, draggableId, type } = result;
if (!destination) {
return;
}
if (
destination.draggableId === source.droppableId &&
destination.index === source.index
) {
return;
}
if (type === "row") {
const draggableRow = this.state.currentRows.find(row => row.id === draggableId);
const newRowOrder = Array.from(this.state.currentRows);
newRowOrder.splice(source.index, 1);
newRowOrder.splice(destination.index, 0, draggableRow);
const newState = {
...this.state,
currentRows: newRowOrder,
};
this.setState(newState);
}
}