How to get size of a component in react-native?

前端 未结 1 569
闹比i
闹比i 2020-12-28 08:57

I know there\'s

Dimensions.get(\'window\');

But what about a arbitrary view that has no dim string? The arbitrary view could have many sub

相关标签:
1条回答
  • 2020-12-28 09:42

    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: '#ffffd', 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);
    
    0 讨论(0)
提交回复
热议问题