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>
      );
    };

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

相关推荐
万少1 小时前
HarmonyOS 开发必会 5 种 Builder 详解
前端·harmonyos
橙序员小站3 小时前
Agent Skill 是什么?一文讲透 Agent Skill 的设计与实现
前端·后端
炫饭第一名5 小时前
速通Canvas指北🦮——基础入门篇
前端·javascript·程序员
王晓枫6 小时前
flutter接入三方库运行报错:Error running pod install
前端·flutter
符方昊6 小时前
React 19 对比 React 16 新特性解析
前端·react.js
ssshooter6 小时前
又被 Safari 差异坑了:textContent 拿到的值居然没换行?
前端
曲折6 小时前
Cesium-气象要素PNG色斑图叠加
前端·cesium
Forever7_6 小时前
Electron 淘汰!新的桌面端框架 更强大、更轻量化
前端·vue.js
不会敲代码16 小时前
前端组件化样式隔离实战:React CSS Modules、styled-components 与 Vue scoped 对比
css·vue.js·react.js
Angelial6 小时前
Vue3 嵌套路由 KeepAlive:动态缓存与反向配置方案
前端·vue.js