在映射 div 上使用选择器

Using a selector on a mapped div

我正在尝试使用 gsap 通过以下代码为我的 .gallery-item 设置动画:

const MoveItMoveIt = () => { 
   gsap.from('.gallery-item', { delay: .4,  duration: 3, y: 110, ease: "elastic(1, 0.5)", stagger: '0.4'}) 
}

我将画廊映射为:

 {pets.map((pets) => {
            return (
              <div className="col-sm-4 gallery-item  text-center">
                <div className="" key={pets.user}>
                  <div className="">
                    snip
                </div>
              </div>
            );
          })}

问题是我收到错误 gsap target not found 我知道这是因为函数在 .gallery-item 存在之前的毫秒内触发,因此函数找不到它。

我尝试了一个 if 语句来查看 .gallery-item 是否存在,然后 运行 函数。但是 if 语句只是告诉我它不存在。我也尝试过使用 setTimeout() 方法无济于事。

如何解决这个计时问题?我这样调用我的函数:

 useEffect(() => {
    getPetInfo();
   
   
    
    MoveItMoveIt()
  }, []);

感谢评论者的帮助。我能够通过将我的 gsap 函数放在我的 api 调用中来解决这个问题。

 async function getPetInfo() {
    const response = await fetch(
      "my webhook url"
    );
    const json = await response.json();
    console.log(json);
    setPets(json.pets);
    MoveItMoveIt()
  }
  const MoveItMoveIt = () => { 
    const box = document.getElementsByClassName('.gallery-item')
      gsap.from('.gallery-item', { delay: .4,  duration: 3, y: 110, ease: "elastic(1, 0.5)", stagger: '0.4'})
  }

它现在可以正常工作了。