问题描述
是否可以获取某个视图的大小(宽度和高度)?例如,我有一个显示进度的视图:
Is it possible to get the size (width and height) of a certain view? For example, I have a view showing the progress:
<View ref='progressBar' style={{backgroundColor:'red',flex:this.state.progress}} />
我需要知道视图的实际宽度才能正确对齐其他视图.这可能吗?
I need to know the actual width of the view to align other views properly. Is this possible?
推荐答案
从React Native 0.4.2开始,View组件具有.传递一个接受事件对象的函数.事件的nativeEvent
包含视图的布局.
As of React Native 0.4.2, View components have an onLayout
prop. Pass in a function that takes an event object. The event's nativeEvent
contains the view's layout.
<View onLayout={(event) => {
var {x, y, width, height} = event.nativeEvent.layout;
}} />
每次调整视图大小时,也会调用onLayout
处理程序.
The onLayout
handler will also be invoked whenever the view is resized.
主要警告是,onLayout
处理程序在组件安装后首先被调用一帧,因此您可能希望隐藏UI,直到计算出布局为止.
The main caveat is that the onLayout
handler is first invoked one frame after your component has mounted, so you may want to hide your UI until you have computed your layout.
这篇关于在React Native中获取视图的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!