React Native獲得View相對於螢幕的座標x,y
阿新 • • 發佈:2018-11-26
React-Native provides a .measure(...)
method (source code) which returns the offsets and width/height of a component. Simply provide a callback function to .measure(...)
:
myComponent.measure( (fx, fy, width, height, px, py) => {
console.log('Component width is: ' + width)
console .log('Component height is: ' + height)
console.log('X offset to frame: ' + fx)
console.log('Y offset to frame: ' + fy)
console.log('X offset to page: ' + px)
console.log('Y offset to page: ' + py)
})
Example...
The following calculates the layout of a custom component after it is rendered:
class MyComponent extends React.component {
render() {
return <View ref="mycomponent" />
}
componentDidMount() {
// Print component dimensions to console
this.refs.mycomponent.measure( (fx, fy, width, height, px, py) => {
console.log('Component width is: ' + width)
console.log('Component height is: ' + height)
console.log('X offset to frame: ' + fx)
console.log('Y offset to frame: ' + fy)
console.log('X offset to page: ' + px)
console.log('Y offset to page: ' + py)
})
}
}