React Native: Getting the position of an element

前端 未结 6 560
太阳男子
太阳男子 2020-11-28 03:08

I am styling an Image component with flexbox to be in the center of the screen which works pretty well. Now I want a second Image component to be d

6条回答
  •  盖世英雄少女心
    2020-11-28 03:58

    React Native provides a .measure(...) method which takes a callback and calls it with the offsets and width/height of a component:

    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  { this.myComponent = view; }} />
        }
        componentDidMount() {
            // Print component dimensions to console
            this.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)
            })        
        }
    }
    

    Bug notes

    • Note that sometimes the component does not finish rendering before componentDidMount() is called. If you are getting zeros as a result from measure(...), then wrapping it in a setTimeout should solve the problem, i.e.:

      setTimeout( myComponent.measure(...), 0 )
      

提交回复
热议问题