React Native学习-measure测量view的宽高值

measure()测量是根据view标签中的ref属性,使用方法如下:

measureWatermarkerImage(){
 this.refs.watermarkerImage.measure((a, b, width, height, px, py) =>
     this.setState({watermarkerImageWidth: width})
  );
}

with:宽;height:高;px:x轴方向距离左边多少像素;py:y轴方向距离上边多少像素;

根据项目需要,如果需要在页面加载完成后进行测量view,就需要使用

componentDidMount() {
    setTimeout(this.measureWatermarkerImage.bind(this));
};

获取视图组件的x,y,宽,高等值.使用RN自带的measure即可.

具体使用:

1 /**
 2  * Created by shaotingzhou on 2017/2/28.
 3  */
 4 /**
 5  * Sample React Native App
 6  * https://github.com/facebook/react-native
 7  * @flow
 8  */
 9 
10 import React, { Component } from 'react';
11 import {
12     AppRegistry,
13     StyleSheet,
14     Text,
15     View,
16 } from 'react-native';
17 
18 
19 export default class One extends Component {
20     render() {
21         return (
22             <View style={styles.container}>
23                 <Text style={styles.welcome} >
24                     ONE
25                 </Text>
26                 <Text style={styles.instructions} ref="myText">
27                     ONE
28                 </Text>
29                 <Text style={styles.instructions}>
30                     ONE
31                 </Text>
32             </View>
33         );
34     }
35 
36     componentDidMount=() =>{
37         setTimeout(this.showMeasure);  //需要在页面加载完毕之后对视图进行测量,所有需要setTimeout
38     }
39     showMeasure = () =>{
40         this.refs.myText.measure((x,y,width,height,px,py) =>
41             alert(x)
42         );
43     }
44 
45 
46 }
47 
48 const styles = StyleSheet.create({
49     container: {
50         flex: 1,
51         justifyContent: 'center',
52         alignItems: 'center',
53         backgroundColor: '#F5FCFF',
54     },
55     welcome: {
56         fontSize: 20,
57         textAlign: 'center',
58         margin: 10,
59     },
60     instructions: {
61         textAlign: 'center',
62         color: '#333333',
63         marginBottom: 5,
64     },
65 });
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容