简体   繁体   中英

(React onScroll) How to trigger onScoll event

I'm trying to animate a business card by altering its opacity depending on its location in the browser, creating somewhat of a fade-in, fade-out look, but this will differ from a keyframes animation as its not timed but purely dependant on the position of the scrollbar (kind of like the Apple product website). I'm doing this in react and am using the onScroll JSX attribute, but it doesn't seem to be firing. Each Card is 100vh in height.

import React, {useState} from 'react'
import './styles.css'
import Card1 from './Card1'

function App() {
  const [idx, setIdx] = useState(1); 
  
  const iterate = () => {
    console.log('scrolled')
  } 

  return (
    <div className="outer-container" onScroll={iterate}>
        <Card1 num = {idx}/> 
        <Card1 num = {idx}/> 
        <Card1 num = {idx}/> 
        <Card1 num = {idx}/> 
        <Card1 num = {idx}/> 
        <Card1 num = {idx}/> 
    </div>); 
}

export default App;

Any help would be much appreciated!

This might be what you're looking for:

import React, { useState, useEffect } from "react";
import "./styles.css";
import Card1 from "./Card1";

function App() {
  const [idx, setIdx] = useState(1);

  useEffect(() => {
    const handleScroll = () => {
      // code here will be executed on the scroll event
    };

    window.addEventListener("scroll", handleScroll);

    return () => window.removeEventListener("scroll", handleScroll);
  }, []);

  const iterate = () => {
    console.log("scrolled");
  };

  return (
    <div className="outer-container" onScroll={iterate}>
      <Card1 num={idx} />
      <Card1 num={idx} />
      <Card1 num={idx} />
      <Card1 num={idx} />
      <Card1 num={idx} />
      <Card1 num={idx} />
    </div>
  );
}

export default App;

Here's a related post with a solution that may help you: Changing styles when scrolling React

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