在Next.js 14 App Router中使用Lenis实现平滑滚动的问题
解决Next.js 14 App Router中Lenis平滑滚动无效的问题
问题分析
你的代码存在几个关键问题导致Lenis无法正常工作:
- 未导入React的
useRef和useEffect钩子,代码会直接报错 - Lenis默认监听
window滚动事件,但你将ref绑定在自定义div容器上,却未在初始化时指定该容器为滚动目标 - 容器缺少必要的CSS样式,无法触发滚动事件
修复步骤
- 导入缺失的React钩子
在文件顶部补充useRef和useEffect的导入:
import { useRef, useEffect } from 'react';
- 指定Lenis的滚动目标容器
初始化Lenis时,通过target参数传入容器ref,让Lenis监听该容器的滚动行为:
const lenis = new Lenis({ duration: 1.2, easing: (t) => Math.min(1, 1.001 - Math.pow(2, -10 * t)), target: lenisRef.current // 指定滚动目标容器 });
- 添加容器必要的CSS样式
在globals.css中给.smooth-scroll类添加样式,确保容器可正常滚动:
.smooth-scroll { height: 100vh; overflow-y: auto; scroll-behavior: auto; /* 禁用原生平滑滚动,避免和Lenis冲突 */ }
完整修正后的代码
'use client'; import { useRef, useEffect } from 'react'; import Lenis from '@studio-freight/lenis'; import Hero from '@/components/Hero'; import SecondSection from '@/components/sections/second/SecondSection'; import ThirdSection from '@/components/sections/ThirdSection'; import FourthSection from '@/components/sections/FourthSection'; import FifthSection from '@/components/sections/FifthSection'; import SixthSection from '@/components/sections/SixthSection'; import SeventhSection from '@/components/sections/SeventhSection'; import SliderComponent from '@/components/slider/slider'; import EighthSection from '@/components/sections/EighthSection'; import Packages from '@/components/sections/Packages'; import HorizontalScroll from '@/components/HorizontalScroll'; import FinestExperience from '@/components/sections/FinestExperience'; import TenthSection from '@/components/sections/TenthSection'; import GreatAdventure from '@/components/sections/GreatAdventure'; import './globals.css'; function Home() { const lenisRef = useRef(null); useEffect(() => { if (!lenisRef.current) return; const lenis = new Lenis({ duration: 1.2, easing: (t) => Math.min(1, 1.001 - Math.pow(2, -10 * t)), target: lenisRef.current }); function raf(time) { lenis.raf(time); requestAnimationFrame(raf); } requestAnimationFrame(raf); return () => { lenis.destroy(); }; }, []); return ( <div ref={lenisRef} className="smooth-scroll"> <main className="flex flex-col"> <Hero /> <SecondSection /> <GreatAdventure /> <ThirdSection /> <FourthSection /> <FifthSection /> <SixthSection /> <HorizontalScroll /> <Packages /> <SeventhSection /> <EighthSection /> <FinestExperience /> <TenthSection /> </main> </div> ); } export default Home;
额外注意事项
- 移除
main标签上的min-h-screen,避免和容器的height:100vh造成高度冲突 - 确保页面内容高度超过容器高度,否则Lenis不会触发平滑滚动
- 若使用Tailwind CSS,可直接在div上写
className="h-screen overflow-y-auto scroll-auto"代替自定义类
内容的提问来源于stack exchange,提问作者Isiteketo Mutau
相关产品推荐
相关产品推荐

