forked from joshbalfour/react-native-inviewport
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
87 lines (77 loc) · 1.94 KB
/
index.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
87
'use strict';
var React = require('react-native');
var window = React.Dimensions.get('window');
var {View, NativeMethodsMixin} = React;
module.exports = React.createClass({
displayName: 'InViewPort',
mixins: [NativeMethodsMixin],
propTypes: {
onChange: React.PropTypes.func.isRequired,
active: React.PropTypes.bool,
delay: React.PropTypes.number
},
getDefaultProps: function () {
return {
active: true,
delay: 100
};
},
getInitialState: function(){
return {
rectTop: 0,
rectBottom: 0
}
},
componentDidMount: function () {
if (this.props.active) {
this.startWatching();
}
},
componentWillUnmount: function () {
this.stopWatching();
},
componentWillReceiveProps: function (nextProps) {
if (nextProps.active) {
this.lastValue = null;
this.startWatching();
} else {
this.stopWatching();
}
},
startWatching: function () {
if (this.interval) { return; }
this.interval = setInterval(this.check, this.props.delay);
},
stopWatching: function () {
this.interval = clearInterval(this.interval);
},
/**
* Check if the element is within the visible viewport
*/
check: function () {
var el = this.refs.myview;
var rect = el.measure((ox, oy, width, height, pageX, pageY) => {
this.setState({
rectTop: pageY,
rectBottom: pageY + height,
rectWidth: pageX + width,
})
});
var isVisible = (
this.state.rectBottom != 0 && this.state.rectTop >= 0 && this.state.rectBottom <= window.height &&
this.state.rectWidth > 0 && this.state.rectWidth <= window.width
);
// notify the parent when the value changes
if (this.lastValue !== isVisible) {
this.lastValue = isVisible;
this.props.onChange(isVisible);
}
},
render: function () {
return (
<View ref='myview' {...this.props}>
{this.props.children}
</View>
);
}
});