React Native获得View相对于屏幕的坐标x,y

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)
        })        
    }
}
展开阅读全文

没有更多推荐了,返回首页