Next.js + Framer Motion页面切换动画异常问题排查求助
问题:Next.js + Framer Motion页面切换动画的滚动异常
当页面滚动位置大于0时,点击导航栏链接(比如从首页跳转到联系页),router.push会先自动滚动到页面顶部,出现怪异的滚动效果后,页面切换动画才开始执行。
已尝试的解决方案及相关代码
1. 给AnimatePresence添加onExitComplete回调
<AnimatePresence mode="wait" onExitComplete={() => { if (typeof window !== "undefined") { window.scrollTo({ top: 0 }); } }} > <motion.div key={router.pathname} className=""> <Component {...pageProps} /> <SlideUp pathname={pathname} /> <SlideDown pathname={pathname} /> </motion.div> </AnimatePresence>
2. 禁用导航链接的自动滚动行为
{navItems.map((link, index) => ( <motion.div variants={menuLinkVars} key={index}> <p suppressHydrationWarning onClick={() => handleClick(link)}> {link.title} </p> </motion.div> ))} const handleClick = (link) => { active.setActiveLink(link.title); router.push(link.href, { scroll: false, }); };
怀疑问题根源:SlideDown/SlideUp组件样式
组件代码如下:
<motion.div className="absolute text-white bottom-0 left-0 w-full h-full bg-black origin-top" initial={{ scaleY: 1 }} animate={{ scaleY: 0 }} exit={{ scaleY: 0, }} transition={{ duration: 0.8, ease: [0.76, 0, 0.24, 1], delay: 0.2 }} > <h1 suppressHydrationWarning>{active.activeLink}</h1> </motion.div>
内容的提问来源于stack exchange,提问作者tomaszM-dev
相关产品推荐
相关产品推荐

