简体   繁体   English

(React onScroll)如何触发onScoll事件

[英](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).我正在尝试根据名片在浏览器中的位置改变其不透明度来为名片制作动画,从而创建淡入淡出的外观,但这与关键帧 animation 不同,因为它不定时但完全依赖于滚动条的 position(有点像 Apple 产品网站)。 I'm doing this in react and am using the onScroll JSX attribute, but it doesn't seem to be firing.我在反应中这样做并使用 onScroll JSX 属性,但它似乎没有触发。 Each Card is 100vh in height.每张卡的高度为 100vh。

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这是一篇相关文章,其中包含可能对您有所帮助的解决方案: 滚动 React 时更改 styles

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

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