React-Native 中 refs 属性的使用方法

Refs属性不能传递

因为并不是像 key一样,refs是一个伪属性,React 对它进行了特殊处理。
如果你向一个由高级组件创建的组件的元素添加 ref应用,那么ref 指向的是最外层容器组件实例的,而不是包裹组件。
但有的时候,我们不可避免要使用refs,官方给出的解决方案是:

传递一个ref回调函数属性,也就是给ref应用一个不同的名字

这里主要讲解获取自定义控件的坐标,这种项目中实际涉及用到的需求使用说明

定义ref的两种写法:

1.ref = {ref_phoneInput => (this.ref_phoneInput = ref_phoneInput)}
2.ref = {'ref_phoneInput'}

相应的,取出ref指向的组件的两种写法:

1.this.currentInput = this.ref_phoneInput.refs.PhoneNumberInput;
2.this.currentInput = this.refs.ref_phoneInput.refs.PhoneNumberInput;

理解this的指向问题

理解示例2

ref : 指向某个子组件
this : 指向当前export的组件本身,
this.refs : 指向当前export的组件的所有子组件
this.refs.ref_phoneInput : 指向当前import的自定义封装组件
this.refs.ref_phoneInput.refs : 指向当前import的自定义封装组件的所有子组件
this.refs.ref_phoneInput.refs.PhoneNumberInput : 指向当前import的自定义封装组件的其中一个子组件

//定义
<PhoneInput
     placeHolder={'请输入手机号'}
     ref={'ref_phoneInput'}
     style={styles.input}
     onChangeText={this.onChangeTextOfPhoneInput.bind(this)}
     onFocus={this.onFocusOfPhoneInput.bind(this)}
 />
//使用
onFocusOfPhoneInput() {
        this.currentInput = this.refs.ref_phoneInput.refs.PhoneNumberInput;
        if (Platform.OS === 'android') {
            this.ref_pwdInput.closeKeyBoard();
            this.ref_VerifyCodeInput.closeKeyBoard();
        }
    }
//计算结果
keyboardWillShow(event) {
        let keyboardHeight = event.endCoordinates.height;
        this.currentInput.measure((ox, oy, width, height, px, py) => {
            if (py + height + keyboardHeight > AppUtils.getScreenHeight()) {
                var top = AppUtils.getScreenHeight() - (py + height + keyboardHeight) - 20;

                Animated.timing(this.state.marginTop, {
                    toValue: top,
                    duration: event.duration,
                    easing: Easing.linear
                }).start();
            }
        });
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,010评论 19 139
  • core package 概要:Core是所有其他包的基础包.它提供了大部分功能包括metadata,templa...
    LOVE小狼阅读 2,653评论 0 3
  • 最近自己一直在回忆。 有人说,好马不吃回头草,估计自己不是匹好马吧。 大学毕业四年了,回过头看看曾经的自己,还是变...
    来恩赵阅读 432评论 1 1
  • 问世间 谁是你前世的注定 谁是你今生的遇见 谁邂逅了你的青春 谁与你浪漫人世间 🦋 谁是你心中永不凋零...
    雪落重阳阅读 542评论 40 62