【图片预览】第一种方式:hooks父组件调用子组件方法(1、子组件中使用useImperativeHandle钩子 2、父组件中使用useRef)【react-viewer】
1、安装:
npm install react-viewer --save
2、组件:ImgViewer/index.tsx
import React, { useState, useImperativeHandle } from 'react' import Viewer from 'react-viewer' interface ImgViewerProps { imgViewerRef: object downloadable?: boolean } const ImgViewer: React.FC<ImgViewerProps> = (props: any) => { const { imgViewerRef, downloadable = true } = props const [visible, setVisible] = useState<boolean>(false) const [activeIndex, setActiveIndex] = useState<number>(0) const [images, setImages] = useState<any[]>([]) useImperativeHandle(imgViewerRef, () => ({ setVisible: setVisible.bind(this, true), // 打开图片查看器 setActiveIndex: (index: number) => setActiveIndex(index), // 设置索引 setImages: (list: Array<object>) => setImages(list) // 图片列表 })) return ( <Viewer visible={visible} images={images} activeIndex={activeIndex} onClose={setVisible.bind(this, false)} onMaskClick={setVisible.bind(this, false)} // 点击遮罩关闭 downloadable={downloadable} // 是否显示下载按钮,默认显示,显示时imgs对象中需要有downloadUrl字段 downloadInNewWindow // 新窗口打开图片 /> ) } export default ImgViewer
3、使用:
import React, { useState, useEffect, useRef } from 'react'
import ImgViewer from '@/components/ImgViewer'
const imgViewerRef = useRef<any>()
// 图片预览 const handleImgPreview = (list: Array<any>, index: number) => { const imgList: Array<object> = list.map(({ alt, src }) => { return { alt, // 文件名 src, // 文件地址 downloadUrl: src, // 支持下载 } }) imgViewerRef.current.setVisible() imgViewerRef.current.setActiveIndex(index) imgViewerRef.current.setImages(imgList) }
数据结构:
[ { "alt": "001.jpg", "src": "http://filegateway.test.mistong.com/api/filecenter/fileService/file/1134557650378359502", "downloadUrl": "http://filegateway.test.mistong.com/api/filecenter/fileService/file/1134557650378359502" }, { "alt": "002.jpg", "src": "http://filegateway.test.mistong.com/api/filecenter/fileService/file/1134557650378359503", "downloadUrl": "http://filegateway.test.mistong.com/api/filecenter/fileService/file/1134557650378359503" }, { "alt": "003每日用户行为.png", "src": "http://filegateway.test.mistong.com/api/filecenter/fileService/file/1134557650378359504", "downloadUrl": "http://filegateway.test.mistong.com/api/filecenter/fileService/file/1134557650378359504" }, { "alt": "004.jpg", "src": "http://filegateway.test.mistong.com/api/filecenter/fileService/file/1134557650378359505", "downloadUrl": "http://filegateway.test.mistong.com/api/filecenter/fileService/file/1134557650378359505" }, { "alt": "006.jpg", "src": "http://filegateway.test.mistong.com/api/filecenter/fileService/file/1134557650378359506", "downloadUrl": "http://filegateway.test.mistong.com/api/filecenter/fileService/file/1134557650378359506" } ]
DOM:
<ImgViewer imgViewerRef={imgViewerRef} />
4、效果:
5、vue中v-viewer插件的使用:图片预览----v-viewer插件的使用
6、react-viewer插件文档:https://www.npmjs.com/package/react-viewer