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}/>