如何在react-native中获取组件的大小?

时间:2015-11-18 02:37:39

标签: react-native

我知道那里

Dimensions.get('window');

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

1 个答案:

答案 0 :(得分:39)

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

我已经设置了一个实现代码here的示例项目:

https://rnplay.org/apps/mbPdZw

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

'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);