-
Notifications
You must be signed in to change notification settings - Fork 84
Expand file tree
/
Copy pathget-snapshot-before-update.js
More file actions
42 lines (39 loc) · 1.12 KB
/
get-snapshot-before-update.js
File metadata and controls
42 lines (39 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class ListaScorrimento extends React.Component {
constructor(props) {
super(props);
this.rifLista = React.createRef();
}
getSnapshotBeforeUpdate(
propsPrecedenti,
statePrecedente
) {
// Stiamo aggiungendo nuovi elementi alla lista?
// Salviamo la posizione dello scroll in modo da poterla aggiustare in seguito.
if (
propsPrecedenti.list.length < this.props.list.length
) {
const lista = this.rifLista.current;
return lista.scrollHeight - lista.scrollTop;
}
return null;
}
componentDidUpdate(
propsPrecedenti,
statePrecedente,
snapshot
) {
// Se snapshot è definito, abbiamo appenan aggiunto nuovi elementi alla lista.
// Aggiustiamo lo scroll in modo che i nuovi elementi non spingano quelli
// preesistenti fuori dallo schermo.
// (snapshot contiene il valore restituito da getSnapshotBeforeUpdate)
if (snapshot !== null) {
const lista = this.rifLista.current;
lista.scrollTop = lista.scrollHeight - snapshot;
}
}
render() {
return (
<div ref={this.rifLista}>{/* ...contenuti... */}</div>
);
}
}