React Native获取组件位置和大小

RN页面中定位或滚动操作时,需要获取元素的大小和位置信息,有几种常用的方法

获取设备屏幕的宽高

import {Dimensions} from 'react-native';
var {height, width} = Dimensions.get('window');


获取元素的大小和位置信息
1. onLayout事件属性

<View onLayout={this._onLayout}><View>
_onLayout = (e) => {
    let {x,y,width,height} = e.nativeEvent.layout
}
// or
import {NativeModules} from 'react-native'
_onLayout = (e) => {
     NativeModules.UIManager.measure(e.target, (x, y, width, height, pageX, pageY)=>{
         // todo
    })
}

x和y表示左上角的顶点坐标,相对于屏幕的左上角(0,0)

2. 元素自带measure方法
在元素上添加ref

<View ref={(ref) => this.chatView = ref}></View>


在componentDidMount方法里添加一个定时器,定时器里再进行测量,否则拿到的数据为0

componentDidMount(){
   setTimeOut(() => {
     this.refs.chatView.measure((x,y,width,height,pageX, pageY) => {
       //todo
       })
   });
}

3. 使用UIManager measure方法

import {
   UIManager,
   findNodeHandle
} from 'react-native'

handleClick = () => {
    UIManager.measure(findNodeHandle(this.buttonRef),(x,y,width,height,pageX,pageY)=>{
        // todo
 })
    
}

在组件上添加引用

<TouchableButton ref={(ref)=>this.buttonRef=ref} onPress={this.handleClick}/>
原文地址:https://www.cnblogs.com/jiuyi/p/10536924.html