简体   繁体   English

限制 animate.css 动画只能出现一次

[英]Limit animate.css animations at only one time

I am using animate.css and react-on-screen npm packages, react-on-screen package is to use TrackVisibility component so I can make a nice fade-in effect.我正在使用animate.cssreact-on-screen npm 包, react-on-screen package 是使用TrackVisibility组件,所以我可以制作一个很好的淡入效果。 But I only want the animation to be done once.但我只希望 animation 完成一次。 But every time when I scroll back to the component and it reappears on the screen the animation is retaken, and it's not such a great UI.但是每次当我滚动回组件并且它重新出现在屏幕上时,animation 都会被重新获取,这并不是一个很好的 UI。 What should I do?我应该怎么办?

You can use the visible prop of the TrackVisibility component in conjunction with the useState hook, to keep track of whether the component has been animated or not.您可以将TrackVisibility组件的visible属性与useState挂钩结合使用,以跟踪组件是否已设置动画。 Once the component has been animated, you can use the animated prop to turn off the animation.为组件设置动画后,您可以使用animated道具关闭 animation。

import { useState } from 'react';
import { TrackVisibility } from 'react-on-screen';

function MyComponent() {
  const [animated, setAnimated] = useState(false);

  return (
    <TrackVisibility onVisible={() => setAnimated(true)}>
      <div className={`my-component ${animated ? '' : 'animated fadeIn'}`}>
        <!-- ... -->
      </div>
    </TrackVisibility>
  );
}

In this example, the first time the MyComponent comes into view, the animated state variable is set to false, and the animation is applied.在此示例中,第一次出现MyComponent时, animated变量 state 设置为 false,并应用 animation。 But when the MyComponent is scrolled out of view and then scrolled back into view, the animated state variable is already set to true, so the animation is not applied again.但是当MyComponent滚出视图然后又滚回视图时, animated变量 state 已经设置为 true,因此不再应用 animation。

It's also worth noting that if you want to make the animation only once you can use the once prop of the TrackVisibility component:还值得注意的是,如果你只想制作一次 animation,你可以使用TrackVisibility组件的once属性:

<TrackVisibility once>

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

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