首页 > 解决方案 > react.js 中的“未找到 GSAP 目标”,动画在热重载时自行发生

问题描述

我正在尝试使用gsapin为元素设置动画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,
  });
};

标签: reactjsgsap

解决方案


首先,我们需要访问我们想要动画的元素。

在 react 中,我们使用useRefhook 来获取组件的引用,然后使用 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>
  );

推荐阅读