圖片預覽:基於react-viewer封裝圖片檢視器
阿新 • • 發佈:2022-03-07
1、安裝:
npminstallreact-viewer--save
2、元件:ImgViewer/index.tsx
import React, { useState, useImperativeHandle } from 'react' import Viewer from 'react-viewer' interface ImgViewerProps { childRef: object downloadable?: boolean } const ImgViewer: React.FC<ImgViewerProps> = (props: any) => { const { childRef, downloadable= true } = props const [visible, setVisible] = useState<boolean>(false) const [activeIndex, setActiveIndex] = useState<number>(0) const [images, setImages] = useState<any[]>([]) useImperativeHandle(childRef, () => ({ setVisible: setVisible.bind(this, true), // 開啟圖片檢視器 setActiveIndex: (index: number) => setActiveIndex(index), //設定索引 setImages: (imgs: Array<object>) => setImages(imgs) // 圖片列表 })) 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 childRef = useRef<any>()
const handleImgPreview = (value: Array<string>, index: number, n: string) => { const imgs: Array<object> = value.map((src) => ({ src, downloadUrl: n })) childRef.current.setVisible() childRef.current.setActiveIndex(index) childRef.current.setImages(imgs) }
DOM:
<ImgViewer childRef={childRef} />
4、效果:
5、vue中viewer外掛的使用:圖片預覽----v-viewer外掛的使用