我正在使用 next@13 并尝试使 Yet-another-react-lightbox(v3.12.2) 的内联轮播每隔几秒导航一次。
这是我尝试过的:
'use client';
import Lightbox, { useController } from 'yet-another-react-lightbox';
import Inline from 'yet-another-react-lightbox/plugins/inline';
export default function MyComponent ({ slides }: Props) {
const { next } = useController();
useEffect(() => {
setTimeout(function () {
next();
}, 3000);
});
return (
<Lightbox
slides={slides}
plugins={[Inline]}
inline={{
style: {...},
}}
carousel={{...}}
/>
);
}
但它不起作用,我收到此错误:
Error: useController must be used within a ControllerContext.Provider
我不知道这个 useController() 钩子内部会是什么上下文。也许这是一个“需要完成的道具增强,但我不太了解有关它的文档。有人有想法吗? 谢谢!!
useController
和其他内部灯箱挂钩只能在灯箱内渲染的组件中使用(即,在通过自定义渲染函数渲染的组件中,或在使用插件添加到灯箱的组件中)
https://yet-another-react-lightbox.com/advanced#Hooks
但是由于在这种情况下你想在灯箱组件之外使用灯箱控制器,所以你需要使用引用来访问控制器。
export default function MyComponent({ slides }: Props) {
const ref = React.useRef<ControllerRef>(null);
React.useEffect(() => {
let mounted = true;
setTimeout(() => {
if (mounted) {
ref.current?.next();
}
}, 3000);
return () => {
mounted = false;
};
});
return (
<Lightbox
slides={slides}
plugins={[Inline]}
controller={{ ref }}
inline={{ style: { ... } }}
/>
);
}