最近产品有个功能是图片上传多张,同时支持拖拽
看了antd的官方文档很开心有 itemRender 属性,直接用项目里,没有效果,后来仔细一看,官方文档是4.16.0 版本才支持,可惜我们项目是3.X, 那咱们就自己实现吧
使用插件 react-beautiful-dnd
<div className="image-upload">
{fileList?.length >= 1 && (
<DragDropContext onDragEnd={onDragEnd}>
<Droppable droppableId="droppable" direction="horizontal" >
{provided => (
<div ref={provided.innerRef} {...provided.droppableProps} >
{fileList.map((item, index) => (
<Draggable key={item.uid} draggableId={item.uid} index={index} >
{provided => (
<div
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
>
<UploadList
listType="picture-card"
onPreview={onPreview}
locale={en_US}
onRemove={onRemove}
items={[item]}
/>
</div>
)}
</Draggable>
) )}
{provided.placeholder}
</div>
)}
</Droppable>
</DragDropContext>
) }
{fileList.length< maxCounts &&
<Upload
{...props}
fileList={null}
listType="picture-card"
beforeUpload={beforeUpload}
multiple
>{uploadButton} </Upload>}
<Modal visible={previewImage} footer={null} onCancel={() => setPreviewImage(null)}>
<img alt="example" src={previewImage} />
</Modal>
</div>
这里注意的点
1.使用uploadButton 按钮时候 不能直接用 onChange 方法,这个方法会循环调接口,批量最好使用批量上传的接口,这里就需要在beforeUpload 做判断处理,这里就不贴代码了,大家自行发挥
2.Droppable 使用的时候可以设置拖拽方向 这里我们用的是水平拖拽 direction="horizontal", 默认是垂直方向
3.Draggable 可以设置是否禁止拖拽 详情页面可以设置 isDragDisabled 属性
4.UploadList 可以设置是否展示删除按钮 showRemoveIcon 设置不展示删除按钮
5.定义全局 uploadingFiles
const beforeUpload = (file, files ) => {
if(!uploadingFiles){
uploadingFiles = []
}
uploadingFiles.push(file)
const totalNum = fileList.length + uploadingFiles?.length //本次上传数量 + 原有数量
if(totalNum > maxCounts){
uploadingFiles = []
return false
}
if(uploadingFiles.length === files.length){
handleUpload()
}
return false
}
6.接口传参需要注意 formData
一个的时候
const formData = new FormData();
formData.append('file',file)
多个的时候 需要使用循环
uploadFiles?.forEach(item => {
formData.append('files',item)
});
7.因为上传了多张图片,如果需要设置第一张图是主图,那我们在图片左上角设置一个主图的小图标,可以使用伪元素 :first-child 或者nth-child(1) 等方式,找到对应结点即可
8.关于拖拽更多的Api介绍 可以参加官网或是 基于react的拖拽组件库react-beautiful-dnd API参数简易说明
9.看了网上其他小伙伴的例子 使用 react-sortable-hoc 实现多行图片拖拽(本人项目只需要一行图片拖拽)。可供参考 react-sortable-hoc实现拖拽效果