简体   繁体   中英

How can I get the ref or info of the React component that is scrolled into view during a vertical scroll using React Scrollbars?

I have several react components vertically stacked inside a container with react Scrollbars to perform scrolling, I would like to perform some action on each of the components independently based on the component that is currently scrolled into view, How can i get this information in react and fire an event or any other way to perform the actions?

 <Scrollbars>
  <Component1/>
  <Component2/>
  <Component3/>
 </Scrollbars>

As shown in the above code,initially on load of screen only Comp1 maybe visible in the view port whereas when the user scrolls down to Comp2 there has to be some action performed inside the Comp2 and it has to re-render. This is the expected behavior.

My solution for this is to have an event fired on scroll of the container(Scrollbars) and listen for the event in the child components, Now to get the components perform some actions when they are scrolled into view ,we can do the following in the function bound to the scroll event inside the component

const ctrRef=this.refs.comp1Ref; //Ref of the component1
const rect=ctrRef.getBoundingClientRect();
const isComponentInView = (
            rect.top <= (window.innerHeight || document.documentElement.clientHeight) && 
            rect.right <= (window.innerWidth || document.documentElement.clientWidth) 
        );
if(isComponentInView){
        this.actionToPerform();
}

Similarly for the other components within the container.

Remember to unbind the events and the functions inside the componentWillUnmount life cycle method of 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