React Native提供了一个.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)

})

示例......

下面计算自定义组件呈现后的布局:

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说明

请注意,有时组件在调用 componentDidMount() 之前未完成渲染 . 如果你从 measure(...) 得到零,那么将它包装在 setTimeout 应该可以解决问题,即:

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

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐