我需要我的动画显示它何时到达视口,下面的逻辑来自堆栈溢出:
import { useInView } from "react-intersection-observer";
import { motion, useAnimation } from "framer-motion";
const Component = () => {
const animation = useAnimation();
const [ref, inView, entry] = useInView({ threshold: 0.1 });
useEffect(() => {
if (inView) {
animation.start("visible");
} else {
animation.start("hidden");
}
}, [animation, inView]);
const variants = {
visible: {
y: 0,
opacity: 1,
transition: { duration: 0.5, delayChilden: 0.2, staggerChildren: 0.1 },
},
hidden: {
y: enter,
opacity: 0,
},
}
return (
<>
<motion.div
ref={ref}
animate={animation}
initial="hidden"
variants={{variants}}>TITLE 1</motion.div>
//---------CONTENTS HERE
<motion.div
ref={ref}
animate={animation}
initial="hidden"
variants={{variants}}>TITLE 2</motion.div>
//---------CONTENTS HERE
<motion.div
ref={ref}
animate={animation}
initial="hidden"
variants={{variants}}>TITLE 3</motion.div>
</>
);
}但是使用变体将动画重用到不同的标题,直到我到达页面的最后一个标题时,动画才会加载。
我认为每个标题都有不同的变体,但这只会使我的代码变得混乱。我该怎么解决这个问题?
发布于 2022-04-08 00:03:16
所以我想出了方法,你所要做的就是有足够多的useAnimation和inView,在我的例子中,你要应用的元素数量是3 useAnimation & inView,用于3个标题
const title1 = useAnimation()
const title2 = useAnimation()
const title3 = useAnimation()
const [ref, inView, entry] = useInView({ threshold: 0.5 });
const [ref1, inView2] = useInView({ threshold: 0.5 });
useEffect(() => {
if (inView) {
animation.start("visible")
} else {
animation.start("hidden");
}
if (inView2) {
animation2.start("visible")
} else {
animation2.start("hidden");
}
}, [inView, inView2]);瞧
https://stackoverflow.com/questions/71790091
复制相似问题