簡體   English   中英

如何在功能性 React 組件中觸發 onScroll

[英]How to trigger onScroll in a functional React component

我正在使用 React Spring Parallax 構建粘性滾動部分,請在此處查看我的演示: https://codesandbox.io/s/parallax-sticky-scroll-2zd58

目前,除了通過單擊按鈕觸發 scrollTo() 之外,此演示正在按我的需要運行。 我想在用戶向上或向下滾動時觸發 scrollTo function,但是,我不知道如何在反應功能組件中實現 onScroll。

我在這里查看了以下問題,但它們沒有滿足我的問題: onScroll in React 功能組件onScroll React cannot trigger

您所需要的只是將滾動更改為真實。 我想這就是你所需要的

像這樣:

<Parallax scrolling={true} pages={3} ref={(ref) => (parallax = ref)}>
  {/* Franchise Sections   */}
  <FranchiseSection offset="0" bg="red" />
  <FranchiseSection offset="1" scrollTo="2" bg="blue" />
  <FranchiseSection offset="2" scrollTo="3" bg="green" />

  <FranchiseContent offset="0" scrollTo="1" />
  <FranchiseContent offset="1" scrollTo="2" />
  <FranchiseContent offset="2" scrollTo="0" />
</Parallax>

這是你之前的代碼

<Parallax scrolling={false} pages={3} ref={(ref) => (parallax = ref)}>
....

更新

至於要討論的可能是這就是你想要實現的。

此處基於 ParallaxLayer 的文檔中沒有 onScroll 道具React-Spring 所以我認為你需要制作一個 function 來監聽瀏覽器中的滾動活動,就像這個示例一樣。 希望它可以幫助你。

...

const FranchiseSection = (props) => {
  const handleScrollTo = () => {
    console.log("scrolled");
  };

  React.useEffect(() => {
    if (props.offset) {
      window.addEventListener("scroll", handleScrollTo);
    }
    return function cleanup() {
      if (props.offset) {
        window.removeEventListener("scroll", handleScrollTo);
      }
    };
  });

  return (
    <div className="franchise-section">
      <ParallaxLayer
        offset={props.offset}
        speed={0}
        style={{ backgroundColor: `${props.bg}` }}
      >
        {props.children}
      </ParallaxLayer>
    </div>
  );
};

...

這是示例的沙箱

Codesandbox - react-parallax Scroll Listen

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM