在 React 项目中使用 glightbox
一、glightbox 介绍
GLightbox是一个纯 javascript 灯箱组件, 可以用于显示图片、Iframes 、内联内容和视频。
功能特性
- 库文件小,Small - only 11KB Gzipped
- 快速自适应,Fast and Responsive - works with any screen size
- 多相册支持,Gallery Support - Create multiple galleries
- 响应式, Response Images Support - Let the browser use the optimal image for the current screen resolution
- 视频支持,Video Support - Youtube, Vimeo and self hosted videos with autoplay
- Inline content support - display any inline content
- Iframe support - need to embed an iframe? no problem
- 键盘支持,Keyboard Navigation - esc, arrows keys, tab and enter is all you need
- 触摸屏支持,Touch Navigation - mobile touch events
- 图像缩放,Zoomable images - zoom and drag images on mobile and desktop
- 提供 API - control the lightbox with the provided methods
- 自定义主题 Themeable - create your skin or modify the animations with some minor css changes
在线示例
二、React项目中使用步骤
1.引入库
// Using a bundler like webpack
import GLightbox from 'glightbox';
import 'glightbox/dist/css/glightbox.min.css';
2.函数组件中使用
重点:在图像加载后初始化,默认使用 .glightbox 选择器
useEffect(() => {
const lightbox = GLightbox();
return () => {
lightbox.destroy();
};
}, [images]);
{images.map(()=>(
<a href="large-path.jpg or url" class="glightbox" data-type="image">
<img src="small-path.jpg" alt="image" />
</a>
))}
3.参数设置
<!-- 单行:One line config -->
<a href="large.jpg" data-glightbox="title: Your title; description: description here; descPosition: left; type: image; effect: fade; width: 900px; height: auto; zoomable: true; draggable: true;"></a>
<!-- Multiple data attributes / You can use the options as separated data attributes -->
<a
href="large.jpg"
data-title="My title"
data-description="description here"
data-desc-position="right"
data-type="image"
data-effect="fade"
data-width="900px"
data-height="auto"
data-zoomable="true"
data-draggable="true"
></a>
<div class="glightbox-desc custom-desc1">
<p>The content of this div will be used as the slide description</p>
<p>You can add links and any HTML you want</p>
</div>
<!-- URL with no extension -->
<a href="https://picsum.photos/1200/800" data-glightbox="type: image">
<img src="small.jpg" alt="image" />
</a>
<!-- OR using multiple data attributes -->
<a href="https://picsum.photos/1200/800" data-type="image">
<img src="small.jpg" alt="image" />
</a>
<!-- Using responsive images: specify sizes and srcset through data attributes in the same way you would with the img tag.-->
<a href="deafult.jpg" class="glightbox6" data-title="Responsive example"
data-description="Your browser will choose the optimal image for the resolution"
data-sizes="(max-width: 600px) 480px, 800px"
data-srcset="img480.jpx 480w img800.jpg 800w">
<img src="small.jpg" alt="image" />
</a>