reactjs - react.js 中的“未找到 GSAP 目标”,动画在热重载时自行发生
问题描述
我正在尝试使用gsap
in为元素设置动画react.js
。
我的代码仅在响应热重载时才有效,并且在控制台中我收到 gsap 的警告说GSAP target not found
const FeaturedText = () => {
const tl = gsap.timeline({ repeat: 0 });
useEffect(() => {
animation(tl);
}, []);
return <S.FeaturedText className="tl">Hi! Some Text</S.FeaturedText>;
};
const animation = (tl) => {
tl.from(".tl", {
opacity: 0,
duration: 1,
x: 100,
ease: "elastic",
delay: 2,
});
};
解决方案
首先,我们需要访问我们想要动画的元素。
在 react 中,我们使用
useRef
hook 来获取组件的引用,然后使用 gsap 对其进行动画处理。
我将解释如何正确地为组件设置动画。
//initialize useRef
let featuredText = useRef(null);
//start animation only when dom components are mounted.
useEffect(() => {
const tl = gsap.timeline({ repeat: 0 });
animation(tl, featuredText);
}, []);
//Animation
const animation = (tl, el) => {
tl.from(el, {
opacity: 0,
duration: 1,
x: 100,
ease: "elastic",
delay: 2,
});
};
//Component to be animated
return (
<S.FeaturedText ref={(el) => (featuredText = el)} className="tl">
Hi! I'm Raghav
</S.FeaturedText>
);
推荐阅读
- c - 如何检查二次探测是否进入无限循环?
- javascript - 反应状态更新但不映射
- html - 为什么与类“容器”紧贴左边缘?
- java - Java SDK 在 aws s3 存储桶中获取特定文件夹大小
- android - Mapbox Map Kotlin 注释插件 - 需要“样式”,找到“样式?”
- flutter - Dart 错误:错误:当前 Dart 运行时不支持导入 dart:mirrors
- laravel - docker中的Laravel应用程序未连接到数据库
- c++ - 原子栅栏必须配对
- c# - 提交后需要进行部分重新加载,以便用户不需要“刷新”或“F5”
- python - 20种不同类型消息的朴素贝叶斯分类只能预测三种不同类型的消息