简体   繁体   English

如何在功能性 React 组件中触发 onScroll

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

I am using React Spring Parallax to build sticky scrolling sections, see my demo here: https://codesandbox.io/s/parallax-sticky-scroll-2zd58我正在使用 React Spring Parallax 构建粘性滚动部分,请在此处查看我的演示: https://codesandbox.io/s/parallax-sticky-scroll-2zd58

Currently, this demo is functioning how I need it to except for the scrollTo() being triggered by clicking the button.目前,除了通过单击按钮触发 scrollTo() 之外,此演示正在按我的需要运行。 I want to trigger the scrollTo function when a user scrolls up or down, however, I can not figure out how to implement onScroll in react functional components.我想在用户向上或向下滚动时触发 scrollTo function,但是,我不知道如何在反应功能组件中实现 onScroll。

I've looked at the following questions here but they did not satisfy my issue: onScroll in React functional component onScroll React cannot trigger我在这里查看了以下问题,但它们没有满足我的问题: onScroll in React 功能组件onScroll React cannot trigger

all you need is change scrolling to be true.您所需要的只是将滚动更改为真实。 I think that's all you need我想这就是你所需要的

like this:像这样:

<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>

this your code before这是你之前的代码

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

UPDATED更新

as to be discussed may be this is what you want to achieve.至于要讨论的可能是这就是你想要实现的。

There's no onScroll props in ParallaxLayer based Documentation here React-Spring .此处基于 ParallaxLayer 的文档中没有 onScroll 道具React-Spring So i think you need to make a function to listen scroll activity in the browser like this sample.所以我认为你需要制作一个 function 来监听浏览器中的滚动活动,就像这个示例一样。 hope it can help you.希望它可以帮助你。

...

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>
  );
};

...

This is the sandbox for sample这是示例的沙箱

Codesandbox - react-parallax Scroll Listen Codesandbox - react-parallax Scroll Listen

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

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