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();
    }
  }

 

 

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐