在React DND(Drag and Drop)中,如果你想在数组中不存在某个元素时进行拖放操作,你需要确保你的拖放逻辑能够正确处理这种情况。以下是一些基础概念和相关解决方案:
假设你有一个数组items
,你想在数组中不存在某个元素时进行拖放操作。以下是一个示例代码:
import React from 'react';
import { useDrag, useDrop } from 'react-dnd';
const ItemTypes = {
ITEM: 'item',
};
const DragItem = ({ id, text, index, moveItem }) => {
const [, drag] = useDrag({
type: ItemTypes.ITEM,
item: { id, index },
});
const [, drop] = useDrop({
accept: ItemTypes.ITEM,
hover(item, monitor) {
if (!ref.current) {
return;
}
const dragIndex = item.index;
const hoverIndex = index;
if (dragIndex === hoverIndex) {
return;
}
const hoverBoundingRect = ref.current.getBoundingClientRect();
const hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2;
const clientOffset = monitor.getClientOffset();
const hoverClientY = clientOffset.y - hoverBoundingRect.top;
if (dragIndex < hoverIndex && hoverClientY < hoverMiddleY) {
return;
}
if (dragIndex > hoverIndex && hoverClientY > hoverMiddleY) {
return;
}
moveItem(dragIndex, hoverIndex);
item.index = hoverIndex;
},
});
const ref = React.useRef(null);
drag(drop(ref));
return (
<div ref={ref} style={{ padding: '10px', border: '1px solid black' }}>
{text}
</div>
);
};
const DragDropContainer = ({ items, moveItem }) => {
return (
<div>
{items.map((item, index) => (
<DragItem key={item.id} {...item} index={index} moveItem={moveItem} />
))}
</div>
);
};
const App = () => {
const [items, setItems] = React.useState([
{ id: 1, text: 'Item 1' },
{ id: 2, text: 'Item 2' },
{ id: 3, text: 'Item 3' },
]);
const moveItem = (dragIndex, hoverIndex) => {
const dragItem = items[dragIndex];
setItems((items) => {
const newItems = [...items];
newItems.splice(dragIndex, 1);
newItems.splice(hoverIndex, 0, dragItem);
return newItems;
});
};
return <DragDropContainer items={items} moveItem={moveItem} />;
};
export default App;
useDrag
和useDrop
钩子来实现拖放功能。DragItem
组件。通过这种方式,你可以确保即使在数组中不存在某个元素时,拖放操作也能正常进行。
领取专属 10元无门槛券
手把手带您无忧上云