在React Native中获取视图的大小 [英] Get size of a View in React Native

查看:262
本文介绍了在React Native中获取视图的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以获取某个视图的大小(宽度和高度)?例如,我有一个显示进度的视图:

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组件具有

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中获取视图的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆