forked from st0ffern/react-native-inview
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
87 lines (76 loc) · 1.75 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
import React, {Component} from 'react'
import PropTypes from 'prop-types'
import {
View,
Dimensions,
NativeMethodsMixin,
} from 'react-native'
class InView extends Component{
constructor(props){
super(props)
this.state ={
rectTop: 0,
rectBottom: 0
}
}
onLayout() {
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(event => this.check(), this.props.delay)
}
stopWatching() {
this.interval = clearInterval(this.interval)
}
check() {
let win = Dimensions.get('window')
let el = this.refs.myview
let rect = el.measureInWindow((x, y, width, height) => {
this.setState({
rectTop: y,
rectBottom: y + height,
rectWidth: x + width,
})
})
let isVisible = (
this.state.rectBottom != 0 && this.state.rectTop >= 0 && this.state.rectBottom <= win.height &&
this.state.rectWidth > 0 && this.state.rectWidth <= win.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} onLayout={event => this.onLayout(event)}>
{this.props.children}
</View>
)
}
}
InView.defaultProps = {
active: true,
delay: 100,
}
InView.propTypes = {
onChange: PropTypes.func.isRequired,
active: PropTypes.bool,
delay: PropTypes.number
}
module.exports = InView