2015-11-18 38 views
8

So che c'èCome ottenere la dimensione di un componente in nativo reattivo?

Dimensions.get('window'); 

Ma che dire di una vista arbitraria che non ha nessuna stringa dim? La vista arbitraria potrebbe avere molte sottoview. La dimensione della vista viene decisa in base allo stile e al layout delle sottoview, ed è difficile calcolare la dimensione dalle sottoview.

risposta

25

È possibile misurare una vista utilizzando la funzione onLayout di cui here e here. Per configurarlo, devi chiamare una funzione onLayout, che accetta un evento e restituisce un oggetto, che contiene l'oggetto nativeEvent. Questo oggetto contiene le coordinate x & e la larghezza e l'altezza della vista.

Ho creato un progetto di esempio l'attuazione del codice di here:

https://rnplay.org/apps/mbPdZw

Qui di seguito è una semplice configurazione che misura la vista:

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

Thanks a lot ~ !! – Rick

+1

Ottima risposta @Nader –

+1

Ottima risposta, ma sono un po 'preoccupato per le prestazioni. Hai idea di come questo potrebbe influire sulla scorrevolezza di un'app? – stinodes

Problemi correlati