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)
        })        
    }
}

猜你喜欢

转载自blog.csdn.net/u010537398/article/details/70272923
今日推荐