Next.js 13中yet-another-react-lightbox内联轮播自动播放报错解决
解决 yet-another-react-lightbox 内联轮播自动切换的上下文错误
问题出在useController的使用范围——它必须在Lightbox组件提供的ControllerContext.Provider内部调用,也就是只能在Lightbox的子组件或插件渲染的内容中使用,你的原代码在Lightbox的父组件里调用,自然会触发上下文错误。
下面是两种可行的解决方案:
方案一:通过组件Ref获取控制器(推荐)
直接通过Lightbox的ref获取控制器实例,在父组件中实现自动切换逻辑:
'use client'; import { useEffect, useRef } from 'react'; import Lightbox from 'yet-another-react-lightbox'; import Inline from 'yet-another-react-lightbox/plugins/inline'; type Props = { slides: Array<{ src: string; alt?: string }>; }; export default function MyComponent({ slides }: Props) { const lightboxRef = useRef<{ controller: { next: () => void } }>(null); useEffect(() => { // 每隔3秒切换到下一张幻灯片 const intervalId = setInterval(() => { lightboxRef.current?.controller.next(); }, 3000); // 组件卸载时清理定时器,避免内存泄漏 return () => clearInterval(intervalId); }, []); return ( <Lightbox ref={lightboxRef} slides={slides} plugins={[Inline]} inline={{ style: {}, // 填入你的内联样式 }} carousel={{}} // 填入你的轮播配置 /> ); }
方案二:将逻辑放在Lightbox的子组件中
创建一个内部组件,在其中使用useController(该组件需作为Lightbox的子内容渲染):
'use client'; import { useEffect } from 'react'; import Lightbox, { useController } from 'yet-another-react-lightbox'; import Inline from 'yet-another-react-lightbox/plugins/inline'; type Props = { slides: Array<{ src: string; alt?: string }>; }; function AutoSwitcher() { const { next } = useController(); useEffect(() => { const intervalId = setInterval(next, 3000); return () => clearInterval(intervalId); }, [next]); return null; // 不需要渲染任何内容 } export default function MyComponent({ slides }: Props) { return ( <Lightbox slides={slides} plugins={[Inline]} inline={{ style: {}, // 填入你的内联样式 content: ({ children }) => ( <> {children} <AutoSwitcher /> </> ), }} carousel={{}} // 填入你的轮播配置 /> ); }
补充说明
- 原代码中的
useEffect没有依赖数组,会导致每次组件渲染都创建新的定时器,改用setInterval并在组件卸载时清理,能避免内存泄漏。 - 方案一的Ref方式更简洁,适合仅需控制轮播切换的场景;方案二更灵活,适合需要在轮播内部处理更多交互逻辑的场景。
内容的提问来源于stack exchange,提问作者Marion
相关产品推荐
相关产品推荐

