react + antDesign封装图片预览组件(支持多张图片)

需求场景:最近在开发后台系统时经常遇到图片预览问题,如果一个一个的引用antDesign的图片预览组件就有点繁琐了,于是在antDesign图片预览组件的基础上二次封装了一下,避免重复无用代码的出现

效果

公共预览组件代码

javascript 复制代码
import React, { useImperativeHandle, forwardRef, useState } from 'react';
import { message, Image } from 'antd';

const ChildComponent = forwardRef((props, ref) => {
const [visible, setVisible] = useState(false);
const [imgList, setImgList] = useState([]);

const showModal = async (list) => {
  setImgList(list);
  if (list.length === 0) {
    message.warning('暂无图片');
  } else {
    setVisible(true);
  }
};

useImperativeHandle(ref, () => ({
   showModal
}));

return (
    <div>
      <div style={{ display: 'none' }}>
        <Image.PreviewGroup preview={{ visible, onVisibleChange: (vis) => setVisible(vis) }}>
          {imgList.map((item) => {
            return <Image src={item.url} />;
          })}
        </Image.PreviewGroup>
      </div>
    </div>
  );
});

export default ChildComponent;

使用方法

  1. 在项目components文件夹下新建preview文件夹

  2. preview文件夹下新建imgs.jsx把以上代码复制粘贴进去

  3. 在需要用到的地方引入

    javascript 复制代码
    import React, { useRef,useState } from 'react';
    import { Button } from 'antd';
    import Imgs from '../../.././components/Preview/imgs';
    
    export default () => {
    const imgsRef = useRef();
    const [imgList, setImgList] = useState([
        {
          name:'图片1',
          url:'https://gw.alipayobjects.com/zos/antfincdn/LlvErxo8H9/photo-1503185912284-5271ff81b9a8.webp'
        },
        {
          name:'图片2',
          url:'https://gw.alipayobjects.com/zos/antfincdn/cV16ZqzMjW/photo-1473091540282-9b846e7965e3.webp'
        },
        {
          name:'图片3',
          url:'https://gw.alipayobjects.com/zos/antfincdn/x43I27A55%26/photo-1438109491414-7198515b166b.webp'
        }
    ]);
    
    //预览图片
    const imgsPreview = (text) => {
        imgsRef.current.showModal(imgList);
    };
    
    return (
        <div>
          <Button onClick={()=>{imgsPreview()}}></Button>
          <Imgs ref={imgsRef} />
        </div>
      );
    };

注:本人前端小白 ,如有不对的地方还请多多指教

相关推荐
陆枫Larry2 小时前
Astro 是什么
前端
是立不是利3 小时前
写给设计师的 CSS 博客美学指南
前端·css
默_笙4 小时前
🏝 Docker 就是"房地产开发":从施工图纸到小区物业的容器化指南
前端·javascript
计算机魔术师4 小时前
Rohan Paul 谈用时间跨度衡量智能体能力,并引用 OpenAI 自动化研究实习生里程碑
前端
kyriewen4 小时前
我手写了个极简版 React Router——才搞懂 v6 为什么砍了这么多 API
前端·javascript·程序员
a1117764 小时前
Shirone 二次元博客主题 开源
前端·开源
IT_陈寒4 小时前
Python的切片赋值把我坑惨了,这不是bug是特性
前端·人工智能·后端
掘金酱5 小时前
【社区公告】致每一位掘友:关于这次调整, 想再说几句
前端·人工智能
CoderLiu5 小时前
程序化工具调用(PTC)与动态工作流引擎:深入大模型工具调用的架构演进与实践
前端·人工智能·后端
码农胖大海5 小时前
我的第一个产品,只有一段提示词
前端·ai编程·产品