|
1 | | -import React from 'react'; |
2 | 1 | import { debounce } from 'lodash-es'; |
| 2 | +import React, { useCallback, useEffect, useRef, useState } from 'react'; |
3 | 3 |
|
4 | 4 | import getScrollPos from '../utils/scroll'; |
5 | 5 |
|
6 | | -export default class LoadInView extends React.PureComponent { |
7 | | - state = { |
8 | | - show: false, |
9 | | - }; |
| 6 | +const LoadInView = ({ children, style, ...props }) => { |
| 7 | + const [show, setShow] = useState(false); |
| 8 | + const el = useRef(null); |
| 9 | + const elPos = useRef(null); |
10 | 10 |
|
11 | | - constructor(props) { |
12 | | - super(props); |
13 | | - this.listen = debounce(this.listen, 50); |
14 | | - } |
| 11 | + useEffect(() => { |
| 12 | + elPos.current = el.current.getBoundingClientRect().top; |
| 13 | + }, []); |
15 | 14 |
|
16 | | - listen = () => { |
17 | | - if (!this.state.show && this.elPos && getScrollPos().y + 600 > this.elPos) { |
| 15 | + const listenFn = useCallback(() => { |
| 16 | + if (!show && elPos.current && getScrollPos().y + 600 > elPos.current) { |
18 | 17 | requestAnimationFrame(() => { |
19 | | - this.setState({ show: true }); |
| 18 | + setShow(true); |
20 | 19 | }); |
21 | 20 | } |
22 | | - }; |
23 | | - |
24 | | - componentDidMount() { |
25 | | - this.elPos = this.el.getBoundingClientRect().top; |
26 | | - |
27 | | - window.addEventListener('scroll', this.listen); |
28 | | - } |
29 | | - |
30 | | - componentWillUnmount() { |
31 | | - window.removeEventListener('scroll', this.listen); |
32 | | - } |
33 | | - |
34 | | - render() { |
35 | | - const { children, style, ...props } = this.props; |
36 | | - return ( |
37 | | - <div |
38 | | - style={{ display: 'inline-block', width: '100%', ...style }} |
39 | | - ref={el => { |
40 | | - this.el = el; |
41 | | - }} |
42 | | - {...props} |
43 | | - > |
44 | | - {this.state.show && children} |
45 | | - </div> |
46 | | - ); |
47 | | - } |
48 | | -} |
| 21 | + }, [show]); |
| 22 | + |
| 23 | + useEffect(() => { |
| 24 | + const listen = debounce(listenFn, 50); |
| 25 | + |
| 26 | + window.addEventListener('scroll', listen); |
| 27 | + |
| 28 | + return () => window.removeEventListener('scroll', listen); |
| 29 | + }, [listenFn]); |
| 30 | + |
| 31 | + return ( |
| 32 | + <div |
| 33 | + ref={el} |
| 34 | + style={{ display: 'inline-block', width: '100%', ...style }} |
| 35 | + {...props} |
| 36 | + > |
| 37 | + {show && children} |
| 38 | + </div> |
| 39 | + ); |
| 40 | +}; |
| 41 | + |
| 42 | +export default LoadInView; |
0 commit comments