有一个主要组件,它包含4个需要移动的组件--我知道,当位置发生变化时,组件的索引应该发生变化--我不知道如何使组件停留在被移动的位置(如果有必要,我可以在代码框中编写代码)
import React, {useState} from 'react';
import CardWeather from '../cardWeather/CardWeather';
import WeatherMap from '../cardWeatherMap/WeatherMap';
import Forecast from '../forecast/Forecast';
import WeatherGrapth from '../weatherGraph/WeatherGraph';
import './main.scss';
import { DragDropContext, Droppable } from 'react-beautiful-dnd';
const Main = () => {
const [components, setComponents] = useState([{
components: {
'component-1': {id: 'comp-1'},
'component-2': {id: 'comp-2'},
'component-3': {id: 'comp-3'},
'component-4': {id: 'comp-4'},
}
}
])
const onDragEnd = (result) => {
const { destination, source } = result
console.log(result)
if (!destination) {
return
}
if (
destination.droppableId === source.droppableId &&
destination.index === source.index
) {
return
}
}
return (
<>
<DragDropContext onDragEnd={onDragEnd}>
<Droppable droppableId="main">
{
(provided) => (
<div className="main-container"
ref={provided.innerRef}
{...provided.droppableProps}
>
<CardWeather />
<Forecast/>
<WeatherGrapth/>
<WeatherMap/>
{provided.placeholder}
</div>
)
}
</Droppable>
<div className="pr">weather app</div>
</DragDropContext>
</>
)
}
export default Main;发布于 2022-02-23 16:04:05
如果您没有设法解决这个问题,您只需重新排列组件状态。
像这样初始化状态似乎毫无意义(对象的数组(?))考虑到您只管理此组件中的一个状态,即一个对象数组。所以你的状态应该是{cmp:'cmp1',id(?):'comp-1'},{cmp:'cmp2',id?:'comp-2'}等等.
无论如何,onDragEnd都会得到包含目标、源、类型和draggableId的结果。查找拖动组件(components.find(cmp => cmp.id === draggableId)),创建原始数组的副本,拼接source.index,并在destination.index中插入拖动的组件。
应该是这样的:
const onDragEnd = ({destination, source, type, draggableId}: DropResult) => {
if (!destination) {
return
}
const draggedCmp = components.find(cmp => cmp.id === draggableId)
if (!draggedCmp) {
return
}
const newCmps = [...components]
newCmps.splice(source.index, 1)
newCmps.splice(destination.index, 0, draggedCmp)
setComponents(newCmps)https://stackoverflow.com/questions/70770537
复制相似问题