zoukankan      html  css  js  c++  java
  • 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}/>
  • 相关阅读:
    20180925-5代码规范
    20180925-4 单元测试,结对
    20180925-6 四则运算试题生成
    20180925-3 效能分析
    20170925-2 功能测试
    20180925-7 规格说明书——吉林市两日游
    20180918-1 词频统计
    第二周例行报告
    iOS开发-CocoaPods使用详细说明
    svn的使用详解
  • 原文地址:https://www.cnblogs.com/jiuyi/p/10536924.html
Copyright © 2011-2022 走看看