React中添加动效

651 阅读1分钟

React 动效


animate.css 是一个来自国外的 CSS3 动画库

  • 预设了抖动(shake)、闪烁(flash)、弹跳(bounce)等多达 60 多种动画效果
  • 官网
  • Github

WOW.js 可以在页面向下滚动的过程中播放这些动画效果

  • 可以为动画设置喜欢的风格、延迟、长度、偏移和迭代
  • 官网
  • Github

操作步骤

  1. 安装依赖
  2. 在 index.js 中 引入 wowjs 和 animate.css
  3. 初始 wow 对象
  4. 给需要运动的 DOM 元素 添加 class wow 和 动画名称

实例代码

  • index.jsx
import React, { useEffect, useState } from "react";
import styles from "./index.less";
import classNames from "classnames";
import "animate.css";
import WOW from "wowjs";

const Animation = () => {
  //相当于componentDidMount()
  useEffect(() => {
    const wow = new WOW.WOW({ live: false });
    wow.init();
  }, []);

  return (
    <div className={styles["animation"]}>
      <div style={{ height: 1600 }}></div>
      <div
        className={classNames({
          [styles["round"]]: true,
          "wow animate__animated animate__flip": true,
        })}
        data-wow-duration="1s"
        data-wow-delay="0.3s"
      >
        <div>动画</div>
      </div>
      <br />
      <br />
      <br />
      <div
        className={classNames({
          [styles["round"]]: true,
          "wow animate__animated animate__fadeInUp": true,
        })}
        data-wow-duration="1s"
        data-wow-delay="0.3s"
      >
        <div>动画</div>
      </div>
      <br />
      <br />
      <br />
      <div
        className={classNames({
          [styles["round"]]: true,
          "wow animate__animated animate__flash": true,
        })}
        data-wow-duration="1s"
        data-wow-delay="0.3s"
      >
        <div>动画</div>
      </div>
    </div>
  );
};

export default Animation;
  • index.less
.animation {
  height: 100%;
  .round {
    width: 200px;
    height: 200px;
    border-radius: 50%;
    background: linear-gradient(48deg, #e589da 0%, #f3b47a 81%, #f67692 100%);
    background-size: 200% 200%;
    background-position: center;
    background-repeat: no-repeat;
    box-shadow: 6px 6px 23px 0px rgba(233, 149, 190, 0.8);
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
  • 演示图