Skip to content

Instantly share code, notes, and snippets.

@1natsu172
Last active November 29, 2018 17:01
Show Gist options
  • Save 1natsu172/6a2cb397894e96e91c83cc49004f3f01 to your computer and use it in GitHub Desktop.
Save 1natsu172/6a2cb397894e96e91c83cc49004f3f01 to your computer and use it in GitHub Desktop.
react-virtualizedでタイムラインコンポーネントを作ろうとしてハマったときの知見 ref: https://qiita.com/1natsu172/items/f779392eac017cec48a4
<List autoHeight={true} ...{listProps} />
...
<WindowScroller>
{({ height, isScrolling, scrollTop, onChildScroll }) => (
<AutoSizer disableHeight={true}>
{({ width }) => (
<List
isScrolling={isScrolling} // ← これ
onScroll={onChildScroll} // ← これ
scrollTop={scrollTop} // ← これ
{...ListProps}
/>
)}
</AutoSizer>
)}
</WindowScroller>
...
...
<List
deferredMeasurementCache={this._renderCache} // ← わたす
rowRenderer={this._renderRow}
{...ListProps}
/>
...
...
_renderRow = ({ index, key, parent, style }) => (
<CellMeasurer {...CellMeasurerProps} >
// ↓ measureがあるので
{({ measure }) => (
<div style={style} className="row">
<Tweet
measure={measure} // ← わたす
/>
</div>
)}
</CellMeasurer>
)
...
// SFC
const Tweet = ({measure,...rest}) => (
<div className="tweetImage">
<img
src={...}
onLoad={measure} // ← ここでね
alt=""
/>
</div>
)
_rowCount = this.state.tweets.length
render() {
return (
<InfiniteLoader
isRowLoaded={this._isRowLoaded}
loadMoreRows={this._loadMoreRows}
rowCount={this._rowCount + 1} // リストアイテム数 + 1
{...InfiniteProps}
>
{({ onRowsRendered, registerChild }) => (
<List
rowCount={this._rowCount + 1} // リストアイテム数 + 1
{...ListProps}
/>
)}
</InfiniteLoader>
)
}
class extends React.Component {
state = {
tweets: [],
isLoading: false,
hasMore: true
}
_isRowLoaded = ({ index }) => !!this.state.tweets[index]
_infiniteRowCount = () =>
!this.state.isLoading && this.state.hasMore
? this.state.tweets.length + 1
: this.state.tweets.length
_listRowCount = () =>
this.state.hasMore ? this.state.tweets.length + 1 : this.state.tweets.length
render() {
return (
<InfiniteLoader
isRowLoaded={this._isRowLoaded}
loadMoreRows={this._loadMoreRows}
rowCount={this._infiniteRowCount()} // ← これ
{...InfiniteProps}
>
{({ onRowsRendered, registerChild }) => (
<List
rowRenderer={this._renderRow}
rowCount={this._listRowCount()} // ← これ
{...ListProps}
/>
)}
</InfiniteLoader>
)
}
_renderRow = ({ index, key, parent, style }) => (
<CellMeasurer {...CellMeasurerProps}>
<div style={style} className="row">
{
// falseが返ってくる => +1した余分なrow
this._isRowLoaded({ index }) ? (
<Tweet {...tweet} />
) : (
<div>loading...</div> // ← インジケーター
)}
</div>
</CellMeasurer>
)
}
<div style={{ display: 'flex' }}>
<div style={{
flex: '1 1 auto',
// or
height: 600px;
}}>
<AutoSizer>
{({ height, width }) => (
<List {...ListProps} />
)}
</AutoSizer>
</div>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment