refactor LazyLoader and fix bug (#3121)
parent
c550a87e01
commit
49a2a14237
@ -1,40 +1,22 @@
|
||||
import React from 'react';
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { useInView } from 'react-intersection-observer'
|
||||
|
||||
export default class extends React.Component {
|
||||
componentDidMount() {
|
||||
if ('IntersectionObserver' in window) {
|
||||
this.attachObserver()
|
||||
} else {
|
||||
this.props.onVisible && this.props.onVisible()
|
||||
}
|
||||
}
|
||||
|
||||
attachObserver() {
|
||||
this.observer = new IntersectionObserver((entries) => {
|
||||
if (entries[0].isIntersecting) {
|
||||
this.props.onVisible && this.props.onVisible()
|
||||
this.observer.unobserve(this.element);
|
||||
}
|
||||
}, {
|
||||
threshold: 0
|
||||
});
|
||||
export default function LazyLoader(props) {
|
||||
const [hasBecomeVisibleYet, setHasBecomeVisibleYet] = useState(false)
|
||||
const { ref, inView } = useInView({
|
||||
threshold: 0,
|
||||
})
|
||||
|
||||
this.observer.observe(this.element);
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
this.observer && this.observer.unobserve(this.element);
|
||||
}
|
||||
useEffect(() => {
|
||||
if (inView && !hasBecomeVisibleYet) {
|
||||
setHasBecomeVisibleYet(true)
|
||||
props.onVisible && props.onVisible()
|
||||
}
|
||||
}, [inView])
|
||||
|
||||
render() {
|
||||
return (
|
||||
<div
|
||||
ref={(el) => { this.element = el }}
|
||||
className={this.props.className}
|
||||
style={this.props.style}
|
||||
>
|
||||
{this.props.children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div ref={ref}>
|
||||
{props.children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue