简体   繁体   English

在 React.js/Gatsby.js 中使用 gsap 为动画定位类名是一种好习惯吗?

[英]Is it good practice to target class names for animations with gsap in React.js/Gatsby.js

I have read the gsap docs for react integration, and it recommends using useRef() s to target elements to animate, like so:我已经阅读了反应集成的 gsap 文档,它建议使用useRef()来定位要动画的元素,如下所示:

const ref = useRef()
gsap.to(ref, {...})

however, this is very inflexible because the ref is limited to the component's file.然而,这是非常不灵活的,因为 ref 仅限于组件的文件。 in gsap you tend to target multiple elements from all around the website like with gsap.timeline() , so it becomes nearly impossible to target multiple refs from multiple components without complex logic like using context api.在 gsap 中,您倾向于像使用gsap.timeline()一样定位来自整个网站的多个元素,因此几乎不可能定位来自多个组件的多个引用,而无需使用上下文 api 等复杂逻辑。

so im wondering if using the old fashioned way of targeting elements with class names in react is the right approach?所以我想知道在 React 中使用以class名定位元素的老式方法是否是正确的方法?

like so inside a useEffect :就像在useEffect里面useEffect

gsap.from('.foo', {...})

because using class names seem to be dealing with direct dom manipulation, and that seem to be bad practice.因为使用类名似乎是在处理直接的 dom 操作,这似乎是不好的做法。

can anyone chime in on this?任何人都可以插话吗?

In general you should avoid using generic selector strings (what you're doing) as the target of tweens in React.通常,您应该避免使用通用选择器字符串(您正在做什么)作为 React 中补间的目标。 Part of the reason why you want to do so is because it's not very reactful and doesn't keep the components strictly to themselves.您想要这样做的部分原因是因为它不是很敏感并且不会严格地将组件保持在自己的状态。 Second, the window reference may not always exist so it would throw warnings (or errors depending on your code) in some circumstances.其次, window引用可能并不总是存在,因此在某些情况下它会抛出警告(或错误,具体取决于您的代码)。

Try to stick to using refs and optionally use selectors from that ref.尝试坚持使用 refs 并可选择使用该 ref 中的选择器。 Doing so kind of gives you the best of both worlds:这样做可以让您两全其美:

const theRef = useCallback((node) => {
  if (!node) return;
  const spans = node.querySelectorAll('span')
  gsap.to(spans, { autoAlpha: 1})
},[])
...
<div ref={theRef}>
  <span />
  <span />
  <span />
</div>

If you have to use generic selector strings, test, test, then test it again under a bunch of different circumstances.如果您必须使用通用选择器字符串,测试,测试,然后在一堆不同的情况下再次测试。 From an animation standpoint, there likely wont be a performance hit, but make sure that garbage is being cleaned up because that can really bog down a site if you don't kill animations on componentUnmount s.从动画的角度来看,可能不会对性能造成影响,但请确保清理垃圾,因为如果您不杀死componentUnmount的动画,这确实会使网站陷入困境。

For a very general intro to React + GSAP this article is a great place to start.对于 React + GSAP 的非常一般的介绍, 这篇文章是一个很好的起点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM