简体   繁体   English

如何使用React Scrollbars在垂直滚动期间获取滚动到视图中的React组件的引用或信息?

[英]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? 我有几个React组件垂直堆叠在带有react滚动条的容器中以执行滚动,我想根据当前滚动到视图中的组件对每个组件分别执行一些操作,如何在react和触发事件或任何其他方式执行操作?

 <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. 如上面的代码所示,最初在屏幕加载时,只有Comp1在视口中可见,而当用户向下滚动到Comp2时,必须在Comp2内部执行某些操作,然后重新渲染。 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 我的解决方案是在容器的滚动条上滚动一个事件(Scrollbars),并在子组件中侦听该事件,现在要让组件在滚动到视图中时执行一些操作,我们可以在绑定到组件内部滚动事件的函数

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. 记住要解除对componentWillUnmount生命周期生命周期方法内的事件和函数的绑定。

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

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