React3 ref

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

猜你喜欢

转载自blog.csdn.net/m0_65634497/article/details/129365305