|
1 |
| -class ScrollingList extends React.Component { |
| 1 | +class ListaScorrimento extends React.Component { |
2 | 2 | constructor(props) {
|
3 | 3 | super(props);
|
4 |
| - this.listRef = React.createRef(); |
| 4 | + this.rifLista = React.createRef(); |
5 | 5 | }
|
6 | 6 |
|
7 |
| - getSnapshotBeforeUpdate(prevProps, prevState) { |
8 |
| - // Are we adding new items to the list? |
9 |
| - // Capture the scroll position so we can adjust scroll later. |
10 |
| - if (prevProps.list.length < this.props.list.length) { |
11 |
| - const list = this.listRef.current; |
12 |
| - return list.scrollHeight - list.scrollTop; |
| 7 | + getSnapshotBeforeUpdate( |
| 8 | + propsPrecedenti, |
| 9 | + statePrecedente |
| 10 | + ) { |
| 11 | + // Stiamo aggiungendo nuovi elementi alla lista? |
| 12 | + // Salviamo la posizione dello scroll in modo da poterla aggiustare in seguito. |
| 13 | + if ( |
| 14 | + propsPrecedenti.list.length < this.props.list.length |
| 15 | + ) { |
| 16 | + const lista = this.rifLista.current; |
| 17 | + return lista.scrollHeight - lista.scrollTop; |
13 | 18 | }
|
14 | 19 | return null;
|
15 | 20 | }
|
16 | 21 |
|
17 |
| - componentDidUpdate(prevProps, prevState, snapshot) { |
18 |
| - // If we have a snapshot value, we've just added new items. |
19 |
| - // Adjust scroll so these new items don't push the old ones out of view. |
20 |
| - // (snapshot here is the value returned from getSnapshotBeforeUpdate) |
| 22 | + componentDidUpdate( |
| 23 | + propsPrecedenti, |
| 24 | + statePrecedente, |
| 25 | + snapshot |
| 26 | + ) { |
| 27 | + // Se snapshot è definito, abbiamo appenan aggiunto nuovi elementi alla lista. |
| 28 | + // Aggiustiamo lo scroll in modo che i nuovi elementi non spingano quelli |
| 29 | + // preesistenti fuori dallo schermo. |
| 30 | + // (snapshot contiene il valore restituito da getSnapshotBeforeUpdate) |
21 | 31 | if (snapshot !== null) {
|
22 |
| - const list = this.listRef.current; |
23 |
| - list.scrollTop = list.scrollHeight - snapshot; |
| 32 | + const lista = this.rifLista.current; |
| 33 | + lista.scrollTop = lista.scrollHeight - snapshot; |
24 | 34 | }
|
25 | 35 | }
|
26 | 36 |
|
27 | 37 | render() {
|
28 | 38 | return (
|
29 |
| - <div ref={this.listRef}>{/* ...contents... */}</div> |
| 39 | + <div ref={this.rifLista}>{/* ...contenuti... */}</div> |
30 | 40 | );
|
31 | 41 | }
|
32 | 42 | }
|
0 commit comments