如何获得本机组件的大小? [英] How to get size of a component in react-native?

查看:48
本文介绍了如何获得本机组件的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有

Dimensions.get('window');

但是,没有暗字符串的任意视图呢?任意视图可以有许多子视图.视图的大小由子视图的样式和布局决定,很难从子视图中计算出大小.

But what about a arbitrary view that has no dim string? The arbitrary view could have many subviews. The size of the view is decided by style and layout of the subviews, and it's hard to calculate the size from subviews.

推荐答案

您可以使用这里.要进行设置,您需要调用onLayout函数,该函数接受一个事件并返回一个对象,该对象包含nativeEvent对象.该对象包含x&y坐标以及视图的宽度和高度.

You can measure a view using the onLayout function mentioned here and here. To set it up, you need to call an onLayout function, which takes an event and returns an object, which contains the nativeEvent object. This object contains the x & y coordinates, as well as the width and height of the view.

我已经建立了一个示例项目,实现了代码此处:

I've set up an example project implementing the code here:

https://rnplay.org/apps/mbPdZw

以下是测量视图的简单设置:

Below is a simple setup that measures a view:

'use strict';

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TouchableHighlight
} = React;

var SampleApp = React.createClass({

  getInitialState() {
        return {
            x: '',
            y: '',
            width: '',
            height: '',
            viewHeight: 100
        }
    },

  measureView(event) {
    console.log('event peroperties: ', event);
    this.setState({
            x: event.nativeEvent.layout.x,
            y: event.nativeEvent.layout.y,
            width: event.nativeEvent.layout.width,
            height: event.nativeEvent.layout.height
        })
    },

    changeHeight() {
        this.setState({
        viewHeight: 200
      })
    },

  render: function() {
    return (
      <View >
       <View onLayout={(event) => this.measureView(event)}  style={{height:this.state.viewHeight, marginTop:120, backgroundColor: 'orange'}}>
                <Text >The outer view of this text is being measured!</Text>
            <Text>x: {this.state.x}</Text>
            <Text>y: {this.state.y}</Text>
            <Text>width: {this.state.width}</Text>
            <Text>height: {this.state.height}</Text>
        </View>

        <TouchableHighlight style={{flexDirection:'row', alignItems: 'center', justifyContent: 'center', padding:15, backgroundColor: '#ddd', marginTop:10}} onPress={() => this.changeHeight() }>
              <Text style={{fontSize:18}}>Change height of container</Text>
        </TouchableHighlight>
      </View>
    );
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 28,
    textAlign: 'center',
    margin: 10,
  }
});

AppRegistry.registerComponent('SampleApp', () => SampleApp);

这篇关于如何获得本机组件的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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