forked from shichongrui/react-native-on-layout
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
36 lines (33 loc) · 1.08 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
import React, { Component } from 'react'
export default Placeholder =>
class OnLayout extends Component {
state = {
initialLayoutRequired: true
}
onLayout = layoutHandler => e => {
const { initialLayoutRequired, dimensions } = this.state
const { width, height } = e.nativeEvent.layout
if (layoutHandler) {
layoutHandler(e)
}
if (initialLayoutRequired) {
// onLayout is sometimes called when width or height are still 0
if (width > 0 && height > 0) {
this.setState({ dimensions: { width, height }, initialLayoutRequired: false })
}
} else {
// onLayout is sometimes called after initial layout with the same dimensions
if (layout.width !== width || layout.height !== height) {
this.setState({ dimensions: { width, height } })
}
}
}
render() {
const { children, onLayout: layoutHandler, ...props } = this.props
return (
this.state.dimensions
? children({ width: this.state.dimensions.width, height: this.state.dimensions.height })
: <Placeholder {...props} onLayout={this.onLayout(layoutHandler)} />
)
}
}