React3 ref

文章介绍了在React中获取组件引用的几种方式,包括传统的字符串ref和回调函数方式,以及现在推荐的React.createRef()方法。字符串ref因效率问题已被弃用,回调函数可能在渲染时产生额外开销,而React.createRef()是目前官方推荐的更安全、高效的方法。
摘要由CSDN通过智能技术生成

1.跟vue  类似获取ref标签  字符串的ref已经过时了(存在效率问题)

render() {
        return (
            <div>
                <input type="text" name="" ref="input1" placeholder='点击按钮提示数据'/>
                <button onClick={this.dome1}>点我提示左侧数据</button>
  
            </div>
        )
    }
    dome1 = () => {
        console.log(this.refs.input1);
    }

(还没写完,干活了)

2.回调函数使用ref  c 为当前元素    直接将input1 挂在到react实例上  使用直接从实例上拿就行

 render() {
        return (
            <div>
                <input type="text" name="" ref={c => this.input1 = c} placeholder='点击按钮提示数据'/>
                <button onClick={this.dome1}>点我提示左侧数据</button>
            </div>
        )
    }
    dome1 = () => {
        console.log(this.input1);
        alert(this.input1.value)
    }

内联函数中的方式 会在页面更新时候 会调用两次 第一次是null  第二次才是dom元素

这是因为在每次渲染时会创建一个新的函数实例,所以React清空旧的ref并且设置新的。通过将ref的回调函数定义成class的绑定函数的方式可以避免上述问题,但是大多数情况下它是无关紧要的。

更改之后就可以避免上边问题

render() {
        return (
            <div>
                <input type="text" name="" ref={this.saveInput} placeholder='点击按钮提示数据'/>
                <button onClick={this.dome1}>点我提示左侧数据</button>
                <input ref={this.input2} onBlur={this.dome2} type="text" name="" id="" placeholder='失去焦点提示数据' />
            </div>
        )
    }
    saveInput = (c) => {
        this.input1 = c
        console.log(c);
    }
    dome1 = () => {
        alert(this.input1.value)
    }

3.React.createRef() 使用ref  目前react最推荐得一种方式

React.createRef()调用后返回一个容器  该容器存储ref节点  该容器只能为一个节点使用 

 input2 = React.createRef()
    render() {
        return (
            <div>
                <input ref={this.input2} onBlur={this.dome2} type="text" name="" id="" placeholder='失去焦点提示数据' />
            </div>
        )
    }
    dome2 = () => {
        console.log(this.input2.current);
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值