Last active: a year ago
LightGallery React component
import LightGallery from 'lightgallery/react';
import 'lightgallery/css/lightgallery.css';
import 'lightgallery/css/lg-zoom.css';
import 'lightgallery/css/lg-thumbnail.css';
import lgThumbnail from 'lightgallery/plugins/thumbnail';
import lgZoom from 'lightgallery/plugins/zoom';
import { forwardRef, useCallback, useImperativeHandle, useRef } from 'react';
export interface LightBoxProps
extends React.DetailedHTMLProps<
React.HTMLAttributes<HTMLDivElement>,
HTMLDivElement
> {
speed?: number;
images: string[];
index?: number;
onAfterClose?: () => void;
onAfterInit?: (instance: LightGalleryInstance) => void;
}
export type ImpertiveHandler = {
lightGallery: LightGalleryInstance | undefined;
};
export interface LightGalleryInstance {
openGallery: (index: number) => void;
}
/**
* 支持移动端触摸的灯箱
*
* @param images 预览的图片地址
* @param onAfterClose 点击遮罩层关闭后回调
* @param onAfterInit 初始化完成后回调
* @param index 打开时的下标
*/
const LightBox = forwardRef<ImpertiveHandler, LightBoxProps>(
(
{ speed = 500, images, index = 0, onAfterClose, onAfterInit, ...rest },
ref
) => {
const lightGallery = useRef<LightGalleryInstance>();
const init = useCallback((detail: { instance: LightGalleryInstance }) => {
if (!detail) return;
onAfterInit?.(detail.instance);
lightGallery.current = detail.instance;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useImperativeHandle(ref, () => ({
lightGallery: lightGallery.current,
}));
return (
<div {...rest}>
<LightGallery
onInit={init}
speed={speed}
plugins={[lgThumbnail, lgZoom]}
index={index}
onAfterClose={onAfterClose}
>
{images.map((img) => (
<a href={img} key={img}>
<img alt="" src={img} />
</a>
))}
</LightGallery>
</div>
);
}
);
export default LightBox;