React3 ref

1. Similar to vue to get the ref tag string ref is outdated (there is an efficiency problem)

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

(I haven't finished writing yet, I'm working on it)

2. The callback function uses ref c as the current element and directly hangs input1 on the react instance, just use it directly from the instance

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

The method in the inline function will be called twice when the page is updated, the first time is null and the second time is the dom element

This is because a new instance of the function is created on each render, so React clears the old ref and sets the new one. The above problem can be avoided by defining the callback function of ref as a binding function of class, but in most cases it is irrelevant.

After the change, the above problems can be avoided

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() Using ref is currently the most recommended way for react

React.createRef() returns a container after the call. The container stores the ref node. The container can only be used for one node. 

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

Guess you like

Origin blog.csdn.net/m0_65634497/article/details/129365305