需求场景:最近在开发后台系统时经常遇到图片预览问题,如果一个一个的引用antDesign的图片预览组件就有点繁琐了,于是在antDesign图片预览组件的基础上二次封装了一下,避免重复无用代码的出现
效果
公共预览组件代码
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;
使用方法
- 在项目components文件夹下新建preview文件夹
- preview文件夹下新建imgs.jsx把以上代码复制粘贴进去
- 在需要用到的地方引入
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> ); };
注:本人前端小白 ,如有不对的地方还请多多指教