"GSAP target not found" in react.js 并且动画在热重载时自行发生

"GSAP target not found" in react.js and animation happens on its own on hot reload

我正在尝试为 react.js 中的 gsap 元素设置动画。

我的代码仅在 React 热重载时有效,并且在控制台中我收到来自 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,
  });
};

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

In react we use useRef hook to get a component's reference and then use gsap to animate it.

我将解释如何为组件设置动画以正确做出反应。

  //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>
  );