【问题标题】:How to get size of a component in react-native?如何在 react-native 中获取组件的大小?
【发布时间】:2015-11-18 02:37:38
【问题描述】:

我知道有

Dimensions.get('window');

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

【问题讨论】:

标签: javascript react-native


【解决方案1】:

您可以使用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);

【讨论】:

  • 很好的答案,但我有点担心性能。您知道这会如何影响应用的流畅度吗?
  • 调用 setState(通过 measureView)将触发另一个渲染并可能创建一个无限循环。在 React Native 中不建议这样做。 github.com/facebook/react/issues/5591
猜你喜欢
  • 2015-10-14
  • 2015-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-20
  • 2018-03-16
  • 2020-05-06
  • 2021-10-25
相关资源
最近更新 更多