Infinite scrolling with React JS

后端 未结 3 1689
遥遥无期
遥遥无期 2020-11-29 16:07

I am looking at ways to implement infinite scrolling with React. I have come across react-infinite-scroll and found it inefficient as it just adds nodes to the DOM and doesn

3条回答
  •  北海茫月
    2020-11-29 16:37

    Basically when scrolling you want to decide which elements are visible and then rerender to display only those elements, with a single spacer element on top and bottom to represent the offscreen elements.

    Vjeux made a fiddle here which you can look at: jsfiddle.

    Upon scrolling it executes

    scrollState: function(scroll) {
        var visibleStart = Math.floor(scroll / this.state.recordHeight);
        var visibleEnd = Math.min(visibleStart + this.state.recordsPerBody, this.state.total - 1);
    
        var displayStart = Math.max(0, Math.floor(scroll / this.state.recordHeight) - this.state.recordsPerBody * 1.5);
        var displayEnd = Math.min(displayStart + 4 * this.state.recordsPerBody, this.state.total - 1);
    
        this.setState({
            visibleStart: visibleStart,
            visibleEnd: visibleEnd,
            displayStart: displayStart,
            displayEnd: displayEnd,
            scroll: scroll
        });
    },
    

    and then the render function will display only the rows in the range displayStart..displayEnd.

    You may also be interested in ReactJS: Modeling Bi-Directional Infinite Scrolling.

提交回复
热议问题