Framer Motion 不更新 scrollYProgress

Framer Motion not updating scrollYProgress

我正在使用 Framer Motion's useViewportScroll hook to track the user's scroll on my page, but it isn't updating. I came across this 文章,其中解释了 Framer Motion 如何使用 document.body.clientHeightwindow.innerHeight 来计算视口滚动。

这篇文章解释了一些 CSS 如何打破这一点,特别是如果 document.body.clientHeight - window.innerHeight <= 0

我似乎无法弄清楚这怎么会不是真的。即使在我的 React 应用程序中根本没有 CSS,该表达式的计算结果为 true。您可以在 this example on CodeSandbox.

中看到它

谢谢!

我认为您看不到更新的原因不是因为 css。
Framer 似乎从 React 中计算出它的状态 standalone。因此,当 Framer 在内部更新其值时。 react 不一定会使用更新后的值触发重新渲染。 (可能这是为了性能)。

您可以通过订阅 Framer 公开的 onChange 处理程序来挂钩状态更改,并设置您感兴趣的状态。

例如scrollYProgress上的onChange会调用setState,触发react重新渲染。

import React from "react";
import { useViewportScroll } from "framer-motion"

const FramerPostionHook = () => {
  const { scrollYProgress } = useViewportScroll();
  const [hookedYPostion, setHookedYPosition] = React.useState(0);
  React.useEffect(()=>{
    // hook into the onChange, store the current value as state.
    scrollYProgress.onChange(v=> setHookedYPosition(v));
  },[scrollYProgress]); //make sure to re-subscriobe when scrollYProgress changes

  return  (<>
  scrollYProgress.current: {scrollYProgress.current}<br/>
  scrollYProgress.hookedYPostion: {hookedYPostion}<br/>
  </>)
}

Sandbox example