简体   繁体   中英

ReactJS - Code only runs on first time only

I'm currently in the process of learning ReactJS and Javascript in general. I have this problem where if I put some Javascript code in the file. it only runs once when I start the test server (or build) but after that it seems to be broken afterwards. I assume this is because of the way ReactJS works and how the Javascript might gets saved or cached? I hope someone can point me in the right direction since this problem occurs with every piece of code I try, below I will post my code. thanks in advance:)

import "./main.css";
import gsap from "gsap";



function Hero() {

let tl = gsap.timeline();
tl.from(".hero--image", { opacity: 0, scale: 0.4 });

  return (
    <div className="container hero--image shadow-sm h100 br">
      <div className="container d-flex h-100 h-md-0 text-reveal">
        <div className="col col-12 col-md-6 d-inline-flex">
          <div className="hero--padding py-md-0 hero--textbox text-white">
            <h1 className="text-left">Title</h1>
            <p>
              Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque
              accumsan in nisl ut hendrerit. Praesent dictum massa lectus, quis
              ullamcorper velit pharetra sed.
            </p>
          </div>
        </div>
        <div className="col col-12 col-md-6 d-none d-md-inline-flex">
          <div className="hero--logo"></div>
        </div>
      </div>
    </div>
  );
}

export default Hero;

fixed code

import ReactDOM from "react-dom";
import "./main.css";
import gsap from "gsap";
import { useRef, useEffect } from "react";

function Hero() {
  const boxRef = useRef();

  useEffect(() => {
    gsap.from([boxRef.current], {
      opacity: 0,
      y: 10,
      duration: 1,
      rotation: 0.001,
      delay: 1,
    });
  });

  return (
    <div className="container hero--image shadow-sm h100 br">
      <div className="container d-flex h-100 h-md-0 text-reveal">
        <div className="col col-12 col-md-6 d-inline-flex">
          <div
            ref={boxRef}
            className="hero--padding py-md-0 hero--textbox text-white"
          >
            <h1 className="text-left">Title</h1>
            <p>
              Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque
              accumsan in nisl ut hendrerit. Praesent dictum massa lectus, quis
              ullamcorper velit pharetra sed.
            </p>
          </div>
        </div>
        <div className="col col-12 col-md-6 d-none d-md-inline-flex">
          <div className="hero--logo"></div>
        </div>
      </div>
    </div>
  );
}

export default Hero;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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