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

查看:34
本文介绍了在 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 组件有一个 onLayout 道具.传入一个接受事件对象的函数.事件的 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 中获取视图的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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