返回

antd Upload + react-sortable-hoc 搞定图片墙拖拽排序

前端

使用 Ant Design 和 React Sortable HOC 实现图片墙拖拽排序功能

在现代网站设计中,图片墙已成为一种常见元素,用于展示用户上传的图片、产品图片等。为了提升用户体验,图片墙往往会加入拖拽排序功能,允许用户根据自己的喜好调整图片顺序。本文将深入探讨如何利用 Ant Design Upload 和 React Sortable HOC 组件实现这一功能。

1. 安装依赖项

首先,你需要安装 Ant Design Upload 和 React Sortable HOC 组件:

npm install antd react-sortable-hoc

2. 创建 React 组件

接下来,创建一个名为 ImageWall 的 React 组件,用于展示图片墙:

import React, { useState } from "react";
import { Upload, message } from "antd";
import { SortableContainer, SortableElement } from "react-sortable-hoc";

const SortableItem = SortableElement(({ value }) => <li>{value}</li>);

const SortableList = SortableContainer(({ items }) => {
  return (
    <ul>
      {items.map((value, index) => (
        <SortableItem key={`item-${index}`} index={index} value={value} />
      ))}
    </ul>
  );
});

const ImageWall = () => {
  const [imageList, setImageList] = useState([]);

  const handleUpload = ({ fileList }) => {
    const newImageList = fileList.map((file) => file.name);
    setImageList([...imageList, ...newImageList]);
  };

  const onSortEnd = ({ oldIndex, newIndex }) => {
    const newImageList = [...imageList];
    newImageList.splice(oldIndex, 1);
    newImageList.splice(newIndex, 0, imageList[oldIndex]);
    setImageList(newImageList);
  };

  return (
    <div>
      <Upload
        multiple
        accept="image/*"
        onUpload={handleUpload}
        onChange={handleUpload}
      >
        <button type="button">选择图片</button>
      </Upload>
      <SortableList items={imageList} onSortEnd={onSortEnd} />
    </div>
  );
};

export default ImageWall;

3. 运行程序

最后,运行应用程序,即可看到具有拖拽排序功能的图片墙。

4. 总结

本文详细介绍了如何使用 Ant Design Upload 和 React Sortable HOC 组件实现图片墙拖拽排序功能。通过遵循本文中的步骤,你可以轻松掌握这项技术,并将其应用到自己的项目中。

常见问题解答

  1. 为什么我的图片不能拖动?

确保你正确安装了 react-sortable-hoc 组件,并且你的组件已包裹在 SortableContainerSortableElement 组件中。

  1. 如何限制用户可以拖动的图片数量?

你可以使用 SortableContainer 组件的 lockAxis 属性来限制拖拽方向,例如:

<SortableContainer lockAxis="y">
  <SortableList items={imageList} onSortEnd={onSortEnd} />
</SortableContainer>
  1. 如何禁用拖拽排序?

你可以使用 SortableContainer 组件的 disableSorting 属性来禁用拖拽排序,例如:

<SortableContainer disableSorting={true}>
  <SortableList items={imageList} onSortEnd={onSortEnd} />
</SortableContainer>
  1. 如何获取拖拽后的图片顺序?

你可以使用 onSortEnd 回调函数获取拖拽后的图片顺序。回调函数将提供 oldIndexnewIndex 参数,表示图片在拖拽前后的索引。

  1. 如何自定义拖拽手柄?

你可以使用 handle 属性来自定义拖拽手柄。例如,你可以为列表项添加一个拖拽图标:

<SortableItem handle=".handle">
  <li>
    <i className="handle">Drag</i>
    {value}
  </li>
</SortableItem>