forked from yamill/react-native-inviewport
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
86 lines (72 loc) · 1.85 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
import React, { Component, PropTypes } from 'react';
import { View, Dimensions, NativeMethodsMixin } from 'react-native';
class InViewPort extends Component {
mixins: [NativeMethodsMixin]
constructor() {
super(props);
this.state = {
rectTop: 0,
rectBottom: 0
};
}
componentDidMount() {
if (this.props.active) {
this.startWatching();
}
}
componentWillUnmount() {
this.stopWatching();
}
componentWillReceiveProps(nextProps) {
if (nextProps.active) {
this.lastValue = null;
this.startWatching();
} else {
this.stopWatching();
}
}
startWatching() {
if (this.interval) { return; }
this.interval = setInterval(this.check, this.props.delay);
}
stopWatching() {
this.interval = clearInterval(this.interval);
}
// Check if the element is within the visible viewport
check() {
const el = this.refs.myview,
rect = el.measure((ox, oy, width, height, pageX, pageY) => {
this.setState({
rectTop: pageY,
rectBottom: pageY + height,
rectWidth: pageX + width,
})
});
const 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() {
return (
<View ref='myview' {...this.props}>
{this.props.children}
</View>
);
}
}
InViewPort.propTypes = {
onChange: React.PropTypes.func.isRequired,
active: React.PropTypes.bool,
delay: React.PropTypes.number
};
InViewPort.defaultProps = {
active: true,
delay: 100
};
export default InViewPort;