如何在React Locomotive Scroll中调用on()方法?
在React Locomotive Scroll中调用
on()方法的实现方式 要调用Locomotive Scroll的on()方法,核心是获取它的实例。在使用LocomotiveScrollProvider的场景下,可以通过官方提供的LocomotiveScrollContext来获取实例,再在合适的时机绑定事件。
修改后的完整代码示例
import { useRef, useEffect, useContext } from 'react'; import { LocomotiveScrollProvider, LocomotiveScrollContext } from 'react-locomotive-scroll'; // 假设demoFour是已导入的样式对象 const YourComponent = () => { const ref = useRef(null); const scrollContext = useContext(LocomotiveScrollContext); const options = { smooth: true, lerp: 0.08, table: { smooth: true }, smartPhone: { smooth: true }, }; useEffect(() => { // 确保scroll实例已完成初始化 if (scrollContext?.scroll) { // 自定义滚动事件处理函数 const handleScroll = (eventData) => { console.log('滚动事件触发:', eventData); // 这里添加你的业务逻辑 }; // 调用on()绑定scroll事件 scrollContext.scroll.on('scroll', handleScroll); // 组件卸载时解绑事件,避免内存泄漏 return () => { scrollContext.scroll.off('scroll', handleScroll); }; } }, [scrollContext]); return ( <LocomotiveScrollProvider options={options} containerRef={ref}> <div className={demoFour.demo_four} data-scroll-container ref={ref}> <div className={demoFour.demo_four__container}> <section className={demoFour.home} data-scroll-section=""></section> </div> </div> </LocomotiveScrollProvider> ); }; export default YourComponent;
关键说明
- 先导入
LocomotiveScrollContext,通过useContext拿到上下文对象,其中的scroll属性就是Locomotive Scroll的原生实例。 - 在
useEffect中判断实例是否存在,避免在初始化完成前调用方法导致报错。 - 支持绑定的事件包括
scroll、call、init等,对应Locomotive Scroll原生支持的事件类型。 - 组件卸载时必须用
off()解绑事件,防止内存泄漏。
内容的提问来源于stack exchange,提问作者Alexsander
相关产品推荐
相关产品推荐

