我想让当前的y position
在document
中改变ui在某些时刻。我用的代码不工作,我不明白为什么。
const [verticalPosition, setVerticalPosition] = useState()
useEffect(() => {
setVerticalPosition(window.scrollY)
}, [window.scrollY])
useEffect(() => {
console.log(verticalPosition)
}, [verticalPosition])
我已经搜索了替代方案,并找到了最复杂的库来做这么简单的事情。所以我想让它这样工作。有人能告诉我这是怎么回事吗?
Thanks in advance
您需要为document.scroll
事件添加一个事件侦听器,如下所示:
const [verticalPosition, setVerticalPosition] = useState()
useEffect(() => {
const onScroll = ()=>{
setVerticalPosition(window.scrollY);
}
document.addEventListener('scroll', onScroll);
return ()=>document.removeEventListener('scroll', onScroll); // cleanup function runs when component is unmounted
}, []); // empty dependency array so it only runs on mount
专业提示
如果您需要在多个组件中使用此行为,那么将其抽象为自定义钩子是很简单的:
// hooks/useScrollY.js
const useScrollY = ()=>{
const [verticalPosition, setVerticalPosition] = useState()
useEffect(() => {
const onScroll = ()=>{
setVerticalPosition(window.scrollY);
}
document.addEventListener('scroll', onScroll);
return ()=>document.removeEventListener('scroll', onScroll);
}, []);
return verticalPosition;
}
export default useScrollY;
// how to use:
import useScrollY from "../hooks/useScrollY"
const MyComponent = ()=>{
const scrollY = useScrollY();
// do something with scrollY
return (
//...
);
}