我使用useViewportScroll钩子来跟踪页面上的用户滚动,但是它没有更新。我看到了这的文章,其中解释了Framer是如何使用document.body.clientHeight和window.innerHeight计算视图滚动的。
本文解释了一些CSS如何能够打破这一点,特别是如果document.body.clientHeight - window.innerHeight <= 0。
我似乎搞不懂这怎么会不是真的。即使在我的react应用程序中根本没有CSS,该表达式的计算结果也为true。你可以在CodeSandbox上的这个例子上看到它。
谢谢!
发布于 2021-01-09 23:15:17
我认为你没有看到更新的原因不是因为任何css。
Framer似乎从react中计算出它的状态独立的。因此,当Framer在内部更新其值时。react不一定会触发带有更新值的重呈现。(这可能是为了性能而做的)。
您可以通过订阅Framer正在公开的onChange处理程序并设置您感兴趣的状态来连接状态更改。
例如,onChange on scrollYProgress将调用setState,触发对重呈现的反应。
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/>
</>)
}https://stackoverflow.com/questions/65647918
复制相似问题