1. onLayout事件属性
// 在元素上设置onLayout属性
<View onLayout={this._onLayout}><View>
_onLayout = (e) => {
let {x,y,width,height} = e.nativeEvent.layout
}
2.measure方法
// 建议使用函数方式设置ref,否则可能会出一些奇怪的错误
<View ref={(ref) => this.ref_view = ref}></View>
// 这里加一个延时,相当于放入异步执行队列,时长不重要
componentDidMount(){
setTimeOut(() => {
this.ref_view.measure((x,y,width,height,pageX, pageY) => {
//todo
})
});
}
3. 使用UIManager measure方法
import { UIManager, findNodeHandle} from 'react-native'
// ref属性参考方法二设置
onClick = () => {
UIManager.measure(findNodeHandle(this.buttonRef),
(x,y,width,height,pageX,pageY)=>{
// todo
})
}
对于ipad的横竖屏旋转,建议将获取位置的方法抽取成函数,然后在componentDidMount及Dimensions的change事件里调用
import {Dimensions} from 'react-native'
componentDidMount() {
Dimensions.addEventListener('change', this.handleDimensions);
setTimeout(() => {
this.getPosition();
}, 100);
}
handleDimensions(dims) {
if (isIpad) {
this.getPosition();
}
}