current position:Home>React - higher order functions and controlled components

React - higher order functions and controlled components

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

One 、 Uncontrolled components : Use it now, take it now

Use a case to expand :

To realize a function like the following figure : enter one user name , password , Click login

 


Pop up the entered account and password value :

 


Code implementation :

<body>
    <div id="root"></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 type="text/babel">
        class Login extends React.Component {
            login = (event) => {
                event.preventDefault()// Block the default behavior of the form -- Jump 
                const { username, password } = this
                alert(` Account No ${username.value},  The password for ${password.value}`)
            }
            render() {
                return (
                    <form action="http://www.baidu.com" onSubmit={this.login}>
                        {/* All input classes in the form dom Value ,( multi-select 、 Single choice counts ) Use it now, take it now , Uncontrolled components */}
                         user name :<input ref={c => this.username = c} type="text" name="username" />
                        {/* Use it now, take it now : Click login to submit the form , call onsubmit Method , Get form data */}
                         The secret &nbsp; code :<input ref={c => this.password = c} type="password" name="password" />
                        <button> Sign in </button>
                    </form>
                )
            }
        }
        ReactDOM.render(<Login />, document.getElementById('root'))
</body>

</html>

Two 、 Uncontrolled components

The same needs , Code implementation :

 <script type="text/babel">
        class Login extends React.Component {
            // 3. Initialization status 
            state = { username: '', password: '' }

            saveUsername = (event) => {
                this.setState({username:event.target.value}) //2. Give its value to the State 
            }
            savePassword = () => {
                this.setState({password:event.target.value})  //2. Give its value to the State 
            }
            login = (event) => {
                event.preventDefault()// Block the default behavior of the form -- Jump 
                // 4. from state Value in 
                const { username, password } = this.state
                alert(` Account No ${username},  The password for ${password}`)
            }
            //  Advantages of controlled components : Can be omitted ref
            render() {
                return (
                    <form action="" onSubmit={this.login}>
                        {/*1.onchange event : Get its value when it changes , similar vue Two way binding in */}
                         user name :<input onChange={this.saveUsername} type="text" name="username" />
                         The secret &nbsp; code :<input onChange={this.savePassword} type="password" name="password" />
                        <button> Sign in </button>
                    </form>
                )
            }
        }
        ReactDOM.render(<Login />, document.getElementById('root'))
    </script>

3、 ... and 、 Higher order function _ currying

Higher order function : If a function conforms to the following 2 Any one of the specifications , Then the function is a higher-order function .

                1. if A function , The received parameter is a function , that A It's called a higher-order function .

                2. if A function , The return value of the call is still a function , that A It's called a higher-order function .

                Common higher-order functions are :Promise、setTimeout、arr.map()

The coriolisation of functions :

Continue to return functions through function calls , Realize the function coding form of multiple received parameters and finally unified processing .

  <script>
        function sum(a, b, c) {
            return (a + b + c)
        }
        console.log(sum(1,2,3))
        
        //  The coriolisation of functions 
        function sum1(a){
            return (b)=>{
                return (c)=>{
                    return a+b+c
                }
            }
        }
        console.log(sum1(1)(2)(3));
    </script>

Code implementation :

 <script type="text/babel">
        // #region  #endregion  Let the code collapse 
        // #region
        /*
             Higher order function : If a function conforms to the following 2 Any one of the specifications , Then the function is a higher-order function .
                1. if A function , The received parameter is a function , that A It's called a higher-order function .
                2. if A function , The return value of the call is still a function , that A It's called a higher-order function .
                 Common higher-order functions are :Promise、setTimeout、arr.map()

             The coriolisation of functions : Continue to return functions through function calls , Realize the function coding form of multiple received parameters and finally unified processing .
        */
        // #endregion
        class Login extends React.Component {
            // 3. Initialization status 
            state = { username: '', password: '' }

            //  The parameter passed from this location is the form data category , For example, user name , password ,id, cell-phone number ...
            // 4. Customize a name and pass it in   dateType
            saveFormDate = (dateType) => {  //saveFormDate It's a higher-order function 
                // 5. Find a way to pass it to a function as onchange Event callback  return A function 
                return (event) => {
                    // {}  The value in the object uses []
                    //  amount to  this.setState({username:event.target.value})
                    //  amount to  this.setState({password:event.target.value})
                    // ...
                    this.setState({ [dateType]: event.target.value })//6. Give its value to the State 
                }
            }

            login = (event) => {
                event.preventDefault()// Block the default behavior of the form -- Jump 
                // 

                 from state Value in 
                const { username, password } = this.state
                alert(` Account No ${username},  The password for ${password}`)
            }
            //  Advantages of controlled components : Can be omitted ref
            render() {
                return (
                    <form action="" onSubmit={this.login}>
                        {/*1.onChange={this.saveFormDate('username')}  Write it yourself to distinguish what is passed in the form of parameters */}
                        {/*2.onChange={this.saveFormDate()}  Add () It's wrong. */}
                        {/*3.onChange={this.saveFormDate}  To pass a function as onchange Event callback ,react To help you call */}
                         user name :<input onChange={this.saveFormDate('username')} type="text" name="username" />
                         The secret &nbsp; code :<input onChange={this.saveFormDate('password')} type="password" name="password" />
                        <button> Sign in </button>
                    </form>
                )
            }
        }
        ReactDOM.render(<Login />, document.getElementById('root'))
    </script>

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

Random recommended