使用FlatList時renderScrollComponent組件的ref問題

ListView的刷新功能大多都是基于自定義renderScrollComponent,然后通過保存ref進(jìn)行一些操作,但是基于這種切換到FlatList會出現(xiàn)找不到ref的問題。

FlatList基于VirtualizedList,通過查看VirtualizedList的代碼發(fā)現(xiàn),VirtualizedList內(nèi)部使用了React.cloneElement函數(shù),并且重新定義了ref。

const ret = React.cloneElement(
      this.props.renderScrollComponent(this.props),
      {
        onContentSizeChange: this._onContentSizeChange,
        onLayout: this._onLayout,
        onScroll: this._onScroll,
        onScrollBeginDrag: this._onScrollBeginDrag,
        ref: this._captureScrollRef,
        scrollEventThrottle: 50, // TODO: Android support
        stickyHeaderIndices,
      },
      cells,
    );

那為啥之前的ListView不會呢? 查看ListView代碼可以看到

 return cloneReferencedElement(renderScrollComponent(props), {
      ref: this._setScrollComponentRef,
      onContentSizeChange: this._onContentSizeChange,
      onLayout: this._onLayout,
    }, header, bodyComponents, footer);

簡單來說使用cloneReferencedElement 可以保留原來的ref。

最后,解決方案------->通過FlatList的ref拿到ScrollComponent。
SectionList沒有驗證,應(yīng)該也是同理,畢竟都是基于VirtualizedList。

this._flatList._listRef._scrollRef
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容