我现在正在学习gsap,我想制作一个可以在每个组件中使用的简单钩子。我希望这个钩子在组件可见时制作动画。这是我的钩子代码:
import { useEffect, useState } from "react";
import { TimelineMax } from "gsap";
const UseOnItemVisible = (ref, callback, scrollPosition) => {
const [wasAnimated, setAnimation] = useState(false);
useEffect(() => {
const tl = new TimelineMax({ paused: true });
if (!wasAnimated) {
const item = ref.current.getBoundingClientRect();
const isItemVisible =
item.top >= 0 && item.bottom <= window.innerHeight + 30;
if (isItemVisible) {
callback(tl.play());
setAnimation(true);
}
}
}, [callback, ref, scrollPosition, wasAnimated]);
};
export default UseOnItemVisible;
我现在可以在任何组件中导入钩子,并为其提供动画回调函数,如下所示:
export const Heading = ({ children }) => {
const headingRef = useRef(null);
const animation = tl => {
tl.to(heading.current, 1, { opacity: 1, y: 0 })
}
UseOnItemVisible(headingRef, animation);
return (
<S.Style ref={headingRef}>
{children}
</S.Style>
);
};
问题是,我必须添加滚动侦听器-我应该在此挂钩中实现吗?现在,我正在App.js中实现它,它看起来像这样:
const App = () => {
const [scrollPosition, setScrollPosition] = useState();
const handler = () => {
const scroll = document.documentElement.scrollTop;
setScrollPosition(scroll);
};
useEffect(() => {
window.addEventListener("scroll", handler);
return () => window.removeEventListener("scroll", handler);
}, []);
UseOnItemVisible(topNavRef, () => console.log("attached"), scrollPosition);
return <Page />
我不确定我是否正确执行了操作。我添加了一些动画,并且网站有时会变慢(我只使用不透明度或变换)。