H5开发,基于 react-photo-view
库,封装实现预览图片、放大缩小图片等功能的业务组件。
- 如果想在web端实现类似且功能相对丰富的可以参考:前端项目实战之web图片预览组件封装
一、安装 react-photo-view
yarn add react-photo-view
或者用 npm
npm install react-photo-view
二、封装 PreviewImages 组件
- 切记引入
import "react-photo-view/dist/react-photo-view.css";
否则会出现样式异常
import { forwardRef, useCallback, useImperativeHandle, useState } from "react";
import { PhotoProvider, PhotoSlider } from "react-photo-view";
import "react-photo-view/dist/react-photo-view.css";
import type { PhotoProviderProps } from "react-photo-view/dist/PhotoProvider";
import { DataType } from "react-photo-view/dist/types";
import { IPhotoSliderProps } from "react-photo-view/dist/PhotoSlider";
export interface PreviewImagesRef {
open: ({ index, urls }: { index: number; urls: string[] }) => void;
close: () => void;
}
type PreviewImagesProps = {
onClose?: () => void;
photoProviderProps?: PhotoProviderProps;
} & Omit<IPhotoSliderProps, "visible" | "images" | "onClose">;
const PreviewImages = forwardRef<PreviewImagesRef, PreviewImagesProps>(
(props, ref) => {
const { photoProviderProps, ...restPhotoSliderProps } = props;
const [visible, setVisible] = useState<boolean>(false);
const [index, setIndex] = useState<number>(0);
const [images, setImages] = useState<DataType[]>([]);
const onIndexChange = useCallback(
(e) => {
setIndex(e);
restPhotoSliderProps?.onIndexChange?.(e);
},
[restPhotoSliderProps]
);
const onClose = useCallback(() => {
setVisible(false);
restPhotoSliderProps?.onClose?.();
}, [restPhotoSliderProps]);
useImperativeHandle(
ref,
() => ({
open: ({ index: _index, urls }) => {
const _images = Array.isArray(urls)
? urls.map((url, i) => ({ src: url || "", key: i }))
: [];
setImages(_images);
setIndex(_index);
setVisible(true);
},
close: onClose,
}),
[onClose]
);
return (
<PhotoProvider {...(props?.photoProviderProps || {})}>
<PhotoSlider
photoClosable={false}
{...(restPhotoSliderProps || {})}
images={images}
index={index}
visible={visible}
onClose={onClose}
onIndexChange={onIndexChange}
/>
</PhotoProvider>
);
}
);
export default PreviewImages;
三、使用
1. 示例
import PreviewImages, { PreviewImagesRef } from "@/components/PreviewImages";
import { useRef } from "react";
const pictures = [
"https://img2.baidu.com/it/u=496754399,526690120&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=904",
"https://img0.baidu.com/it/u=355339949,1813470147&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=904",
"https://img2.baidu.com/it/u=1612188668,496483824&fm=253&fmt=auto&app=138&f=JPEG?w=1278&h=800",
"https://img0.baidu.com/it/u=696957468,70087051&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=599",
];
const TestPreviewImagesComp = () => {
const previewRef = useRef<PreviewImagesRef>(null);
return (
<div>
<button
onClick={() => previewRef.current?.open({ urls: pictures, index: 0 })}
>
打开图片预览
</button>
<PreviewImages ref={previewRef} />
</div>
);
};
export default TestPreviewImagesComp;