基于 antd Upload 组件的图片墙实现拖拽排序
以下是一个使用Ant Design的Upload组件和react-dnd实现图片墙拖拽的简化示例:
import React, { useState } from 'react';
import { Upload, Icon, Modal, Button } from 'antd';
import { DndProvider, useDrag, useDrop } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import 'antd/dist/antd.css';
const { Dragger } = Upload;
const ItemTypes = { IMAGE: 'image' };
function ImageItem({ isDragging, index, item, moveItem, removeItem }) {
const ref = useDrag({
item: { type: ItemTypes.IMAGE, index, id: item.id },
collect: (monitor) => ({
isDragging: monitor.isDragging(),
handlerId: monitor.getHandlerId(),
}),
});
const [, drop] = useDrop({
accept: ItemTypes.IMAGE,
hover(item, monitor) {
if (item.type === ItemTypes.IMAGE && index !== monitor.getItem().index) {
moveItem(item.index, index);
item.index = index;
}
},
});
const opacity = isDragging ? 0.4 : 1;
return (
<div ref={(ref) => drop(ref)} style={{ opacity }}>
<img src={item.url} alt={item.name} style={{ width: '100%' }} />
<Button onClick={() => removeItem(index)}>Remove</Button>
</div>
);
}
const ImageWall = () => {
const [images, setImages] = useState([
{ id: 1, url: 'image1.jpg' },
{ id: 2, url: 'image2.jpg' },
// ...
]);
const moveItem = (oldIndex, newIndex) => {
setImages((items) => {
if (oldIndex === newIndex) return items;
const newItems = [...items];
const [removed] = newItems.splice(oldIndex, 1);
newItems.splice(newIndex, 0, removed);
return newItems;
});
};
const removeItem = (index) => {
setImages((items) => items.filter((_, i) => i !== index));
};
return (
<DndProvider backend={HTML5Backend}>
<div style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'space-around' }}>
{images.map((item, index) => (
<ImageItem
key={item.id}
index={index}
item={item}
moveItem={moveItem}
removeItem={removeItem}
/>
))}
</div>
</DndProvider>
);
};
export default ImageWall;
这段代码使用了react-dnd
评论已关闭