/
list.tsx
70 lines (61 loc) · 1.82 KB
/
list.tsx
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import React, { useEffect, useRef, useState } from 'react';
import { useHistory } from 'react-router';
import { KeepAliveAssist } from 'keep-alive-comp';
import './styles.css';
export interface ListProps extends KeepAliveAssist {}
const List: React.FC<ListProps> = ({
beforeRouteLeave,
scrollRestore,
stateRestore,
}) => {
const history = useHistory();
const listRef = useRef<HTMLDivElement | null>(null);
const [scrollTop, setScrollTop] = useState(0);
const [list, updateList] = useState([]);
useEffect(() => {
restore();
}, []);
const restore = () => {
const _scrollTop = scrollRestore();
const _state = stateRestore();
updateList(
() => _state?.list || ['111111', '222222', '333333', '444444', '555555']
);
setTimeout(() => {
listRef.current.scrollTop = _scrollTop;
}, 0);
};
const onScroll = (e: any) => {
e.persist();
const top = e.target.scrollTop;
setScrollTop(top);
const scrollHeight = listRef.current.scrollHeight;
const offsetHeight = listRef.current.offsetHeight;
if (scrollHeight - offsetHeight - top <= 50) {
const temp = new Array(5)
.fill('')
.map((i, index) =>
new Array(6).fill(`${list.length + index + 1}`).join('')
);
updateList((prev) => [...prev, ...temp]);
}
};
const toDetail = (item) => {
beforeRouteLeave(scrollTop, { list });
history.push(`/detail/${item}`);
};
return (
<div className="list" ref={listRef} onScroll={onScroll}>
{list.map((item, index) => (
<div
className={`item ${index % 2 === 0 ? 'item-2n' : ''}`}
key={item}
onClick={() => toDetail(item)}
>
{item}
</div>
))}
</div>
);
};
export default List;