current position:Home>[entry DIARY 7 - ref of react]

[entry DIARY 7 - ref of react]

2022-04-29 05:17:45Little fool I

One 、【react learning ref】

1. In string form ref

demand :


  The code is as follows :

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="root1"></div>
    <script src="../node_modules/react/umd/react.development.js"></script>
    <script src="../node_modules/react-dom/umd/react-dom.development.js"></script>
    <script src="../js/babel.min.js"></script>
    <script src="../js/prop-types.js"></script>
    <script type="text/babel">
        class Person extends React.Component {
            // 2. To assign + Write the event method here in the way of arrow function 
            showData = () => {
                console.log(this); // this There are refs attribute 
                console.log('this.refs', this.refs);
                // 4. Get the actual input
                const { input1 } = this.refs
                // 5. eject 
                alert(input1.value)
            }
            showData2 = () => {
                const { input2 } = this.refs
                alert(input2.value)
            }

            render() {
                return (
                    //  In string form ref
                    // 1. Add event , Write event method 
                    // 3. add ref attribute 
                    <div>
                        <input ref="input1" type="text" />
                        <button onClick={this.showData}> Click to pop up the text </button>
                        <input ref="input2" onBlur={this.showData2} type="text" placeholder=" Lose focus, pop up text " />
                    </div>
                )
            }
        }

        ReactDOM.render(<Person />, document.getElementById('root1'))
    </script>
</body>

</html>

String form is not recommended ref, Too many references, low efficiency .

2. In the form of callbacks ref

The same requirement calls... In the form of a callback ref Write about the , Pay attention to the notes

 <script type="text/babel">
        class Person extends React.Component {
            showData = () => {
                //  Get the actual input
                //  From the example (this) Take it on your body 
                const { input1 } = this
                //  eject 
                alert(input1.value)
            }
            showData2 = () => {
                const { input2 } = this
                alert(input2.value)
            }
            render() {
                console.log(this);  // 1.2 Test it : Let's see who executed it   //this:Person Instance object 
                return (
                    //  In the form of callbacks ref
                    // 1. add ref attribute 
                    //  Callback function : I defined , I didn't call , Carried out 
                    // 1.1 Test it : Let's see if it's implemented 
                    // <input ref={(a)=>{console.log(a);}} type="text" />   // Find out a yes ref The binding of dom node 
                    // 2. Write a callback , stay this An attribute is bound to the instance input1, The property value is input node 
                    //  in other words , hold a The node represented is placed on the component instance itself , Give an attribute name input1
                    //  Give examples (this) Put one on your body input1 attribute 
                    // <input ref={a => this.input1 = a} type="text" /> 
                    //  summary :ref={ Callback function }    Callback function React Call... For you 
                    <div>
                        <input ref={a => this.input1 = a} type="text" />
                        <button onClick={this.showData}> Click to pop up the text </button>
                        <input ref={a => this.input2 = a} onBlur={this.showData2} type="text" placeholder=" Lose focus, pop up text " />
                    </div>
                )
            }
        }

        ReactDOM.render(<Person />, document.getElementById('root1'))
    </script>

To sum up : How to use string form and callback form ref Get dom Node , From the above two pieces of code , The string form is through ref="input1" In the form of ref On ,React Put it on the instance object refs In the attribute , adopt this.refs.input1 Get input node .

Callback is in the form of ref={a => this.input1 = a} In the form of , Placed on the instance object (this Point to instance object ) On , Add a... To the instance object input1 attribute , adopt this.input1 Get input node .

Callback ref Frequency problem :

  <script type="text/babel">
        class Person extends React.Component {

            state = { happy: true }
            showData = () => {
                const { input1 } = this
                alert(input1.value)
            }
            changeHappy = () => {
                const { happy } = this.state
                this.setState({ happy: !happy })
            }
            showInfo = (a) => {
                this.input1 = a; console.log('@', a)
            }
            render() {
                console.log(this);
                const { happy } = this.state
                return (
                    <div>
                     {/*  notes :1. How to write inline functions :<input ref={a => { this.input1 = a; console.log('@', a) }} type="text" />  */}
                        <h2> Today is very {happy ? ' Happy ' : ' unhappy '}</h2>
                        {/*  notes :2. How to define a class binding function :*/}
                        <input ref={this.showInfo} type="text" />
                        <button onClick={this.showData}> Click to pop up the text </button>
                        <button onClick={this.changeHappy}> Click me to switch my mood </button>
                    </div>
                )
            }
        }

        ReactDOM.render(<Person />, document.getElementById('root1'))
    </script>

(1) The callback function executes several times ?

answer :2 Time , Look at the official website for callback refs Explanation ,( There are many ways to write inline in development )

3.createRef Use

    <script type="text/babel">
        class Person extends React.Component {
            // 1. establish Ref Containers 
            //  amount to a = 1 ;  Add an attribute to the instance a,  The property value is  1
            //  myRef = React.createRef()  Add an attribute to the instance myRef
            // React.createRef() After calling, a container is returned , The container is stored by ref The identified node , The container is specially designed for special personnel 
            myRef = React.createRef()
            myRef2 = React.createRef()
            showData = () => {
                console.log(this.myRef); //this.myRef There is a fixed attribute  current
                alert(this.myRef.current.value)//3.this.myRef.current Get the node , then .value Value 
            }
            showData2 = () => {
                alert(this.myRef2.current.value)
            }
            render() {
                return (
                    <div>
                        {/* 2. add ref attribute  */}
                        <input ref={this.myRef} type="text" />
                        <button onClick={this.showData}> Click to pop up the text </button>
                        <input ref={this.myRef2} onBlur={this.showData2} type="text" placeholder=" Lose focus, pop up text " />
                    </div>
                )
            }
        }
        ReactDOM.render(<Person />, document.getElementById('root1'))
    </script>

Be careful : Try to avoid string Ref, It is recommended on the official website createRef

4. Don't overuse ref

   <script type="text/babel">
        class Person extends React.Component {
            // 1. establish Ref Containers 
            myRef = React.createRef()
            myRef2 = React.createRef()
            showData = () => {
                alert(this.myRef.current.value)
            }
            //  adopt event.target Get information about what happened DOM Element object 
            // event.target  The source of the event 
            // event  The event object of the event 
            showData2 = (event) => {
                console.log(event);
                alert(event.target.value)
            }
            render() {
                return (
                    <div>
                        <input ref={this.myRef} type="text" />
                        <button onClick={this.showData}> Click to pop up the text </button>
                        {/*  Don't overuse ref, Sometimes you can omit , When the element of the event happens to be the element to be operated, it can be omitted ref*/}
                        <input onBlur={this.showData2} type="text" placeholder=" Lose focus, pop up text " />
                    </div>
                )
            }
        }
        ReactDOM.render(<Person />, document.getElementById('root1'))
    </script>

copyright notice
author[Little fool I],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/116/202204261122079516.html

Random recommended