【问题标题】:How can I get the ref or info of the React component that is scrolled into view during a vertical scroll using React Scrollbars?如何使用 React Scrollbars 获取在垂直滚动期间滚动到视图中的 React 组件的引用或信息?
【发布时间】:2019-07-02 09:44:23
【问题描述】:
我有几个反应组件垂直堆叠在带有反应滚动条的容器内以执行滚动,我想根据当前滚动到视图中的组件独立地对每个组件执行一些操作,我如何获取此信息在反应和触发事件或任何其他方式来执行操作?
<Scrollbars>
<Component1/>
<Component2/>
<Component3/>
</Scrollbars>
如上面的代码所示,最初加载屏幕时,只有 Comp1 可能在视口中可见,而当用户向下滚动到 Comp2 时,必须在 Comp2 内部执行一些操作,并且必须重新渲染。这是预期的行为。
【问题讨论】:
标签:
javascript
jquery
css
reactjs
【解决方案1】:
我对此的解决方案是在容器(滚动条)的滚动上触发一个事件并在子组件中侦听该事件,现在要让组件在滚动到视图时执行一些操作,我们可以这样做在绑定到组件内部的滚动事件的函数中跟随
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();
}
容器内的其他组件也是如此。
记得解绑react的componentWillUnmount生命周期方法里面的事件和函数。