Scrolling issues with FlatList when rows are variable height

后端 未结 4 2061
时光说笑
时光说笑 2021-02-01 08:11

I\'m using a FlatList where each row can be of different height (and may contain a mix of both text and zero or more images from a remote server).

I cannot

4条回答
  •  一向
    一向 (楼主)
    2021-02-01 08:34

    Use scrollToOffset() instead:

        export default class List extends React.PureComponent {
    
            // Gets the total height of the elements that come before
            // element with passed index
            getOffsetByIndex(index) {
                let offset = 0;
                for (let i = 0; i < index; i += 1) {
                    const elementLayout = this._layouts[i];
                    if (elementLayout && elementLayout.height) {
                        offset += this._layouts[i].height;
                    }
                }
                return offset;
            }
    
            // Gets the comment object and if it is a comment
            // is in the list, then scrolls to it
            scrollToComment(comment) {
                const { list } = this.props;
                const commentIndex = list.findIndex(({ id }) => id === comment.id);
                if (commentIndex !== -1) {
                    const offset = this.getOffsetByIndex(commentIndex);
                    this._flatList.current.scrollToOffset({ offset, animated: true });
                }
            }
    
            // Fill the list of objects with element sizes
            addToLayoutsMap(layout, index) {
                this._layouts[index] = layout;
            }
    
            render() {
                const { list } = this.props;
    
                return (
                     item.id}
                        renderItem={({ item, index }) => {
                            return (
                                 {
                                        this.addToLayoutsMap(layout, index);
                                    }}
                                >
                                    
                                
                            );
                        }}
                        ref={this._flatList}
                    />
                );
            }
        }
    
    1. When rendering, I get the size of each element of the list and write it into an array:

    onLayout={({ nativeEvent: { layout } }) => this._layouts[index] = layout}

    1. When it is necessary to scroll the screen to the element, I summarize the heights of all the elements in front of it and get the amount to which to scroll the screen (getOffsetByIndex method).

    2. I use the scrollToOffset method:

    this._flatList.current.scrollToOffset({ offset, animated: true });

    (this._flatList is ref of FlatList)

提交回复
热议问题