Brian Vaughn
7 years ago
4 changed files with 109 additions and 11 deletions
@ -0,0 +1,19 @@ |
|||
class Example extends React.Component< |
|||
Props, |
|||
State, |
|||
Snapshot |
|||
> { |
|||
static getDerivedStateFromProps( |
|||
nextProps: Props, |
|||
prevState: State |
|||
): $Shape<State> | null { |
|||
// ...
|
|||
} |
|||
|
|||
getSnapshotBeforeUpdate( |
|||
prevProps: Props, |
|||
prevState: State |
|||
): Snapshot { |
|||
// ...
|
|||
} |
|||
} |
@ -0,0 +1,35 @@ |
|||
class ScrollingList extends React.Component { |
|||
listRef = null; |
|||
|
|||
// highlight-range{1-8}
|
|||
getSnapshotBeforeUpdate(prevProps, prevState) { |
|||
// Are we adding new items to the list?
|
|||
// Capture the current height of the list so we can adjust scroll later.
|
|||
if (prevProps.list.length < this.props.list.length) { |
|||
return this.listRef.scrollHeight; |
|||
} |
|||
return null; |
|||
} |
|||
|
|||
// highlight-range{1-8}
|
|||
componentDidUpdate(prevProps, prevState, snapshot) { |
|||
// If we have a snapshot value, we've just added new items.
|
|||
// Adjust scroll so these new items don't push the old ones out of view.
|
|||
if (snapshot !== null) { |
|||
this.listRef.scrollTop += |
|||
this.listRef.scrollHeight - snapshot; |
|||
} |
|||
} |
|||
|
|||
render() { |
|||
return ( |
|||
<div ref={this.setListRef}> |
|||
{/* ...contents... */} |
|||
</div> |
|||
); |
|||
} |
|||
|
|||
setListRef = ref => { |
|||
this.listRef = ref; |
|||
}; |
|||
} |
@ -0,0 +1,36 @@ |
|||
class ScrollingList extends React.Component { |
|||
listRef = null; |
|||
prevScrollHeight = null; |
|||
|
|||
// highlight-range{1-7}
|
|||
componentWillUpdate(nextProps, nextState) { |
|||
// Are we adding new items to the list?
|
|||
// Capture the current height of the list so we can adjust scroll later.
|
|||
if (this.props.list.length < nextProps.list.length) { |
|||
this.prevScrollHeight = this.listRef.scrollHeight; |
|||
} |
|||
} |
|||
|
|||
// highlight-range{1-9}
|
|||
componentDidUpdate(prevProps, prevState) { |
|||
// If prevScrollHeight is set, we've just added new items.
|
|||
// Adjust scroll so these new items don't push the old ones out of view.
|
|||
if (this.prevScrollHeight !== null) { |
|||
this.listRef.scrollTop += |
|||
this.listRef.scrollHeight - this.prevScrollHeight; |
|||
this.prevScrollHeight = null; |
|||
} |
|||
} |
|||
|
|||
render() { |
|||
return ( |
|||
<div ref={this.setListRef}> |
|||
{/* ...contents... */} |
|||
</div> |
|||
); |
|||
} |
|||
|
|||
setListRef = ref => { |
|||
this.listRef = ref; |
|||
}; |
|||
} |
Loading…
Reference in new issue