首页 > 解决方案 > 检查组件是否在视口中:无限渲染

问题描述

我想检查特定组件是否在视口中,它似乎正在工作,但该组件正在无限渲染。

  componentDidMount() {
    document.addEventListener('scroll', this.checkViewPort,true);
 }

 componentWillUnmount() {
    document.removeEventListener('scroll', this.checkViewPort);
 }


 checkViewPort = () => {

    const rect = this.scrollRef.getBoundingClientRect();
    const isInview = ( rect.bottom < 0 || rect.right < 0 || rect.left > window.innerWidth || 
   (rect.top) > window.innerHeight);
     this.setState({hintViewPort:!isInview});
 }
   setWrapperRef = (node) => {
    this.scrollRef = node;
 };


   <div ref = {this.setWrapper}> </div>

标签: javascriptreactjsreact-redux

解决方案


推荐阅读