Next.js中simple-react-lightbox点击图片无法全屏无响应怎么办
问题修复方案
目标实现的全屏灯箱效果参考:
点击无响应由三个写法错误导致:
- 自定义App组件未接收框架传入的
Component、pageProps参数,直接引用pageProps会造成SimpleReactLightbox全局上下文传递失效,灯箱核心逻辑未完成初始化 SRLWrapper默认仅扫描内部href指向图片资源的原生<a>标签作为灯箱触发节点,直接渲染Next.js<Image />组件时无对应锚点标记,组件无法绑定点击触发事件- Next.js
<Image />使用layout="fill"模式时强制要求父容器设置position: relative,否则图片渲染位置、层级异常,会直接阻断交互
修正后可运行代码
自定义App组件(对应pages/_app.js文件)
import SimpleReactLightbox from 'simple-react-lightbox' const MyApp = ({ Component, pageProps }) => { return( <SimpleReactLightbox> <Component {...pageProps} /> </SimpleReactLightbox> ) } export default MyApp
图集Collection组件
import { CollectionStyledTypography } from './styles/collectionStyledComponents' import { SRLWrapper } from 'simple-react-lightbox' import Image from 'next/image' const Collection = ({ imagesList = [] }) => { return ( <SRLWrapper> <div style={{ margin: '50px' }}> {imagesList.map((image, index) => ( <CollectionStyledTypography component="div" key={index} style={{ position: 'relative' }} > <a href={image.src} style={{ display: 'block', width: '100%', height: '100%' }} > <Image src={image.src} alt={image.alt} layout="fill" /> </a> </CollectionStyledTypography> ))} </div> </SRLWrapper> ) } export default Collection
替换代码后重启Next.js开发服务即可正常触发灯箱,如需自定义灯箱的快捷键、按钮样式、轮播逻辑,可传入
options属性到SRLWrapper或SimpleReactLightbox组件做配置。
内容的提问来源于stack exchange,提问作者Motsi
相关产品推荐
相关产品推荐

