我试图使用Framer和反应相交观测器包将相同的动画分配给一个组件的多个实例
import { useEffect, useRef, useCallback } from "react";
import { motion, useAnimation } from "framer-motion";
import { useInView } from "react-intersection-observer";
const levels = [
{
title: "GROUP LESSONS",
description:
"Lorem ipsum",
},
{
title: "WORKSHOPS",
description:
"Lorem ipsum",
},
];
const container = {
show: {
transition: {
staggerChildren: 0.2,
},
},
};
const item = {
hidden: { opacity: 0, x: 200 },
show: {
opacity: 1,
x: 0,
transition: {
ease: [0.6, 0.01, -0.05, 0.95],
duration: 1.6,
},
},
};
const Levels = () => {
const animation = useAnimation();
const [levelRef, inView] = useInView({
triggerOnce: true,
});
useEffect(() => {
if (inView) {
animation.start("show");
}
}, [animation, inView]);
return (
<LevelsContainer>
{levels.map((level, index) => {
return (
<LevelsWrapper
key={index}
ref={levelRef}
animate={animation}
initial="hidden"
variants={container}
>
<Level variants={item}>
<Title>{level.title}</Title>
<Description>{level.description}</Description>
</Level>
</LevelsWrapper>
);
})}
</LevelsContainer>
);
};这导致只有在滚动到最后一个LevelWrapper组件时才会加载动画。然后"inView“设置为true,所有组件同时动画。在react交集-观察者包文档中,有一些关于在单个useCallback中包装多个参考作业的信息,所以我尝试过:
const animation = useAnimation();
const ref = useRef();
const [levelRef, inView] = useInView({
triggerOnce: true,
});
const setRefs = useCallback(
(node) => {
ref.current = node;
levelRef(node);
},
[levelRef]
);
useEffect(() => {
if (inView) {
animation.start("show");
}
}, [animation, inView]);
return (
<LevelsContainer>
{levels.map((level, index) => {
return (
<LevelsWrapper
key={index}
ref={setRefs}
animate={animation}
initial="hidden"
variants={container}
>
<Level variants={item}>
<Title>{level.title}</Title>
<Description>{level.description}</Description>
</Level>
</LevelsWrapper>
);
})}
</LevelsContainer>
);但是对于每个LevelWrapper组件,动画仍然不能单独触发。发生什么事了呢?
发布于 2022-02-14 15:18:00
不知道为什么问题中的代码不起作用,但我发现不需要使用useEffect、useRef、useCallback、useAnimation或useInView就可以达到最终结果。
在Framer Motion文档中:
动作扩展了由简单而强大的UI手势识别器所提供的事件侦听器的基本集合。 它目前支持悬停,点击,潘,视口和拖曳手势检测。每个手势都有一系列事件侦听器,您可以将其附加到运动组件上。
然后应用此处解释的内容:https://www.framer.com/docs/gestures/#viewport-options
<LevelsWrapper
key={index}
initial="hidden"
whileInView="show"
variants={container}
viewport={{ once: true, amount: 0.8, margin: "200px" }}
>https://stackoverflow.com/questions/71113730
复制相似问题