滚动到底部/行与autosizer和cellmeasurer进行反应虚拟化

时间:2017-08-31 17:11:02

标签: reactjs react-virtualized

我正在构建一个聊天应用程序并使用react-virtualized来管理聊天消息的显示/无限负载(通过自定义方法,而不是HOC)。我正在使用Autosizer来填充容器div,并使用cellmeasurer来计算行高。一切都很好,除非我试图向下滚动到列表底部的最后/最新消息时,它在我身边才会出现。通常,底行的下一行是可见的,我需要向下滚动一点以查看实际的底行。

以下是相关摘要:

渲染方法:

render() {
    const hasNextPage = this.props.contact ? this.props.contact.messages.length < this.props.contact.totalMessageCount : false
    // const totalMessageCount = this.props.contact ? this.props.contact.totalMessageCount : 0
    const contactMessages = this.props.contact ? sortBy(this.props.contact.messages, "created_at") : []
    const rowCount = contactMessages.length // hasNextPage ? contactMessages.length + 1 : contactMessages.length

    // auto resizer copy-spiration
    // https://github.com/bvaughn/tweets/blob/37d0139736346db16b9681d5b859a4e127964518/src/components/TweetList.js#L126-L132
    const _rowRenderer = ({ index, key, parent, style }) => {
      let content;
      if (index === 0 && hasNextPage) {
        content = 'Loading...'
      } else {
        content = <ChatMessage message={contactMessages[index]} />
      }

      return (
        <CellMeasurer
          cache={this._cache}
          columnIndex={0}
          key={key}
          parent={parent}
          rowIndex={index}
          width={this._mostRecentWidth}
        >
          <div
            key={key}
            style={style}
          >
            {content}
          </div>
        </CellMeasurer>
      );
    };

    return (
      <div style={{ height: '65vh' }}>
        <AutoSizer>
          {({ height, width }) => (
            <List
              deferredMeasurementCache={this._cache}
              // eslint-disable-next-line no-return-assign
              ref={ref => this.chatWindow = ref}
              onRowsRendered={(renderData) => this.handleRowsRendered(renderData, hasNextPage, rowCount)}
              rowRenderer={_rowRenderer}
              height={height}
              width={width}
              rowHeight={this._cache.rowHeight}
              rowCount={rowCount}
            />
          )}
        </AutoSizer>

      </div>
    )
  }

我呼吁在componentDidUpdate上滚动:

componentDidUpdate() {
    if (this.chatWindow && !this.state.initialized && this.props.contact) {
      // this.chatWindow.recomputeRowHeights(this.props.contact.messages.length - 10)
      this.chatWindow.scrollToRow(this.props.contact.messages.length || 0)
    }
  }

任何想法如何实现该列表的少量滚动以使底部消息可见?

1 个答案:

答案 0 :(得分:0)

我在List中遇到了同样的问题,方法是使用将estimatedRowSize参数设置为我的平均行大小值的方法来解决该问题。

<List     
 rowHeight={this.getRowHeight}
 rowRenderer={this.rowRenderer}
 onRowsRendered={this.onRowsRendered}
 rowCount={totalRows}
 // Row size It may vary in my case it is 44.5. 
 // Also it doesnt need to be exact.
 //Approx value will work but estimated row size should not be less than actual row height. 
 estimatedRowSize={44.5}
 overscanRowCount={10}
 height={height}
 width={width}
/>