-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlazyImg.jsx
55 lines (48 loc) · 1.14 KB
/
lazyImg.jsx
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
/**
* image lazyload
*/
import React from 'react'
const ref = 'lazyload'
export default class LazyImg extends Component {
static PropTypes = {
src: PropTypes.string.isRequired
}
constructor(props) {
super(props);
this.loadImg = this.loadImg.bind(this);
this.state = {
buffer: 10
}
}
loadImg () {
if (!this.props.src) {
return
}
let image = new Image()
image.onload = () => {
this.setState({
src: this.props.src
})
}
image.src = this.props.src
}
componentDidMount () {
const self = this
self.scrollHandler = () => {
let buffer = self.props.buffer
if (self.refs[ref].getBoundingClientRect().top < window.innerHeight + buffer) {
window.removeEventListener('scroll', self.scrollHandler, true)
self.loadImg()
}
}
window.addEventListener('scroll', self.scrollHandler, true)
self.scrollHandler()
}
componentWillUnmount () {
window.removeEventListener('scroll', this.scrollHandler, true)
this.scrollHandler = null
}
render () {
return <img src={this.state.src} {...props} ref={ref} />
}
}