/
React-lazyload.js
86 lines (69 loc) · 2.56 KB
/
React-lazyload.js
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
'use strict';
//关于react延迟加载
let React = require('react');
// utils
let _ = require('underscore');
let StyleMarker = require('react-style-marker');
module.exports = React.createClass({
getInitialState() {
return {
visible: false
}
},
handleScrollInnter() {
let coverDom = this.refs.preCoverDOM;
// 加载界限中,额外提供的1000px
let extraOffset = 1000;
if (coverDom) {
let bounds_ = this.refs.preCoverDOM.getDOMNode().getBoundingClientRect();
if (bounds_.top <= (window.innerHeight + extraOffset)
&& bounds_.bottom > -extraOffset) {
this.handleVisible();
this.setState({visible: true});
}
}
},
handleVisible() {
// 添加/移除事件全部使用捕获的模式
window.removeEventListener('scroll', this.handleScroll, true);
window.removeEventListener('resize', this.handleScroll, true);
// 自定义事件
if (this.props.selfDefinedEvent) {
window.removeEventListener(this.props.selfDefinedEvent, this.handleScroll, true);
}
},
componentDidMount() {
this.handleScroll = _.throttle(this.handleScrollInnter, 200, {trailing: false});
window.addEventListener('scroll', this.handleScroll, true);
window.addEventListener('resize', this.handleScroll, true);
// 自定义事件
if (this.props.selfDefinedEvent) {
window.addEventListener(this.props.selfDefinedEvent, this.handleScroll, true);
}
this.handleScroll();
},
componentDidUpdate: function () {
if (!this.state.visible) this.handleScroll();
},
componentWillUnmount: function () {
this.handleVisible();
},
render() {
let url = this.props.url;
let styleClass = this.props.styleClass;
let height = this.props.height || 100;
let width = this.props.width || 100;
let T = StyleMarker.trans;
T('myImageSize=width(' + width + ') + height(' + height + ')');
// TODO : 添加默认图片显示
return this.state.visible ? (
<img src={url} className={styleClass || ''} />
) : (
<div>
<div className='clear-both'></div>
<div style={T('myImageSize')} className='clear-both' ref='preCoverDOM'> </div>
<div className='clear-both'></div>
</div>
);
}
});