首页 > 解决方案 > Animate on scroll using react.js

问题描述

I am using some css animations from animate.css and I'm using react.js which works fine at the top of my page however, I also have some animations near the middle of the page. When my page loads everything animates at once which means once I scroll down the animations in the middle of the page have already completed. I am looking for away to delay the animations until that area of the screen is visible. I have found some questions/answers on here but they date back quite a few years and appear to be outdated.

As seen in the code below the animate__animated animate__bounce animate__zoomInDown classes are derived from animate.css but play immediately when the page is loaded and not when visible onscreen:

import React from "react";
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faHourglassStart} from '@fortawesome/free-solid-svg-icons'



function MiddleContainer() {
  return (
    <div>
    <div id = "middle-container" class="middle-container">
      <h1>What can I offer you?</h1>
      <div className = "fast animate__animated animate__bounce animate__zoomInDown">
      <FontAwesomeIcon className="social-icon" icon={faHourglassStart} size = '4x' color = "black"/>
      <h4>Fast and Reliable Service</h4>
      <p>Your product will be delivered to you with precision, care and in a timely manner.</p>
      <p>Add more info here when you are done with the css. </p>
      </div>
      </div>
      </div>
  )
}

export default MiddleContainer;

标签: javascripthtmlcssreactjs

解决方案


所以我能够自己使用不同的库来解决这个问题,因为我在 animate.css 中找不到任何关于如何在滚动上制作动画的文档

带有有效文档的新库是来自https://michalsnik.github.io/aos/的 AOS

我必须使用 react.js 中的 useEffect 才能使其工作。

这是我在滚动工作时使用动画的代码:

import React, { useEffect } from "react";
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faHourglassStart} from '@fortawesome/free-solid-svg-icons'
import AOS from "aos";
import "aos/dist/aos.css";



    function MiddleContainer() {

      useEffect(() => {
        AOS.init({
          // duration : 5000
        });
      }, []);
      return (
    
        
        
        <div>
        <div id = "middle-container" class="middle-container">
          <h1>What can I offer you?</h1>
          <div className = "fast" data-aos="zoom-in">
          <FontAwesomeIcon className="social-icon" icon={faHourglassStart} size = '4x' 
           color = "black"/>
          <h4>Fast and Reliable Service</h4>
          <p>Your product will be delivered to you with precision, care and in a 
           timely manner.</p>
          <p>Add more info here when you are done with the css. </p>
          </div>
    
          
        </div>
    </div>
      )
    }
    
    export default MiddleContainer;

推荐阅读