You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React-scroll在Framer Motion动画元素内失效如何解决?

问题根因

两个库本身不存在底层兼容性问题,失效的核心原因是motion.div的translateY动画属性导致react-scroll计算锚点偏移量出错:

  • react-scroll在组件挂载时会预计算触发跳转的Link元素和目标Element元素的相对位置,当Link位于motion.div内部时,motion.div挂载时初始translateY为1000,react-scroll记录的Link初始位置是偏移后的错误值。动画结束后Link实际位置已经归位到0,但react-scroll没有自动更新位置缓存,就会导致跳转逻辑出错。
  • 把ScrollDiv移到motion.div外部时,Link的位置不会受translateY动画影响,预计算的位置是正确的,所以功能正常。

修复方案

  • 方案1:动画结束后手动刷新react-scroll的位置缓存
    给motion.div添加onAnimationComplete回调,动画结束后调用react-scroll的scroller.update()方法刷新位置缓存,示例代码:
import { scroller } from 'react-scroll'

<motion.div
      animate={{
        translateY: [1000, 0]
      }}
      transition={{ duration: 1 }}
      onAnimationComplete={() => scroller.update()}
    >
      <BottomSection>            
        <ScrollDiv>
          <Link to="scroll-down" spy={true} smooth={true} offset={50} duration={500}>
            Scroll
          </Link>
        </ScrollDiv>
      </BottomSection>
    </motion.div>
    
    <Space top="_360" bottom="_360" />

    <Element name="scroll-down">
    </Element>
  • 方案2:点击跳转时实时计算位置,不依赖预计算缓存
    不使用Link组件的内置跳转,手动绑定点击事件调用scroller.scrollTo方法,每次点击时实时计算位置,避免缓存误差:
import { scroller } from 'react-scroll'

<ScrollDiv>
  <div style={{cursor: 'pointer'}} onClick={() => {
    scroller.scrollTo('scroll-down', {
      spy: true,
      smooth: true,
      offset: 50,
      duration: 500
    })
  }}>
    Scroll
  </div>
</ScrollDiv>
  • 方案3:调整Framer Motion动画实现方式
    把translateY数组动画换成用initial + animate的y属性声明,同时开启layout属性自动同步布局变化:
<motion.div
  initial={{ y: 1000 }}
  animate={{ y: 0 }}
  transition={{ duration: 1 }}
  layout
>
  {/* 原有内部代码保持不变 */}
</motion.div>

内容的提问来源于stack exchange,提问作者wellick53

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 17:15:04