[React] < JavaScript framework > Event Processing & high-order function & function coritization

Posted by Stickdragon on Sun, 30 Jan 2022 15:03:49 +0100

catalogue

1, Event handling:

2, Collect form data:

1. Controlled components:

2. Uncontrolled components:

3, Higher order function & coritization of function:

1. Function coritization:

Overview of coritization:

Application of coritization:

 2. No coritization:

1, Event handling:

  • Specify the event handler function through the onXxx attribute (note case)
    • React uses custom (composite) events instead of native DOM events (for better compatibility)
    • Events in React are handled through event delegation (delegated to the outermost element of the component) (more efficient)
  • Via event Target gets the DOM element object of the event (not overly dependent on ref)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="test"></div>
</body>
<script src="./js/react.development.js"></script>
<script src="./js/react-dom.development.js"></script>
<script src="./js/babel.min.js"></script>
<script src="./js/prop-types.js"></script>
<script type="text/babel">

    //Create component:
    class Demo extends React.Component{
        render(){
            return (
                <div>
                    <input onBlur={this.showData} ref={this.myRef} type="text" placeholder="Click the button to prompt data"/>&nbsp;
                </div>
            )
        }

        //Pass in event and specify the current element node (search and control component)
        showData = (event)=>{
            console.log(event.target)
            alert(event.target.value)
        }
    }

    //Render component to page:
    ReactDOM.render(<Demo/>,document.getElementById("test"))
</script>
</html>

2, Collect form data:

Component categories containing forms:

  • Controlled components
  • Uncontrolled components

1. Controlled components:

Maintain the data in the state. When you need to use it, get the data from the state!

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>2_Controlled components</title>
</head>
<body>
<!-- Prepare a "container" -->
<div id="test"></div>

<!-- introduce react Core library -->
<script type="text/javascript" src="./js/react.development.js"></script>
<!-- introduce react-dom,Used to support react operation DOM -->
<script type="text/javascript" src="./js/react-dom.development.js"></script>
<!-- introduce babel,Used to jsx Turn into js -->
<script type="text/javascript" src="./js/babel.min.js"></script>

<script type="text/babel">
    //Create component
    class Login extends React.Component{

        //Initialization status
        state = {
            username:'', //user name
            password:'' //password
        }

        //Save user name to status
        saveUsername = (event)=>{
            this.setState({username:event.target.value})
        }

        //Save password to status
        savePassword = (event)=>{
            this.setState({password:event.target.value})
        }

        //Callback for form submission
        handleSubmit = (event)=>{
            event.preventDefault() //Block form submission
            const {username,password} = this.state
            alert(`The user name you entered is: ${username},The password you entered is: ${password}`)
        }

        render(){
            return(
                <form onSubmit={this.handleSubmit}>
                    user name:<input onChange={this.saveUsername} type="text" name="username"/>
                    password:<input onChange={this.savePassword} type="password" name="password"/>
                    <button>Sign in</button>
                </form>
            )
        }
    }
    //Rendering Components 
    ReactDOM.render(<Login/>,document.getElementById('test'))
</script>
</body>
</html>

2. Uncontrolled components:

"Use now and take now" component!!!

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="test"></div>
</body>
<script src="./js/react.development.js"></script>
<script src="./js/react-dom.development.js"></script>
<script src="./js/babel.min.js"></script>
<script src="./js/prop-types.js"></script>
<script type="text/babel">

    //Create component:
    class Login extends React.Component{

        render(){
            return (
                <form action="#" onSubmit={this.handleSubmit}>
                    user name:<input ref={c => {this.username = c}} type="text" name="username"/><br/>
                    dense&nbsp;&nbsp;&nbsp;Code:<input ref={c => {this.password = c}} type="text" name="password"/><br/>
                    <button>Sign in</button>
                </form>
            )
        }

        //Callback function:
        handleSubmit = (event)=>{
            event.preventDefault() //Prevent triggering control default effects
            const {username, password} = this
            alert(`user name: ${username.value}  password: ${password.value}`)
        }
    }

    //Render component to page:
    ReactDOM.render(<Login/>, document.getElementById("test"))

</script>
</html>

3, Higher order function & coritization of function:

If a function conforms to any of the following two specifications, the function is a high-order function.

  • If the parameter received by A function is A function, then A can be called A higher-order function.
  • If the return value of A function call is still A function, then A can be called A higher-order function.

Common high-order functions include Promise, setTimeout, arr.map()

1. Function coritization:

Coriolism of function: the function coding form of receiving parameters for many times and finally unified processing is realized by continuing to return the function through function call.

Overview of coritization:

In computer science, Currying is a technology that transforms a function that accepts multiple parameters into a function that accepts a single parameter (the first parameter of the original function), and returns a new function that accepts the remaining parameters and returns the result.

Coriolism technology is mainly reflected in the return function in the function. It is to disassemble multivariable functions into multiple functions of single variable (or partial variable) and call them in turn.

To be more straightforward: using closures, you can form a private scope that will not be destroyed, store the preprocessed content in the scope that will not be destroyed, and return a function, which will be executed in the future.

Application of coritization:

Coriolis has three common applications:

  • Parameter reuse – when the same function is called multiple times and most of the parameters passed are the same, the function may be a good candidate for coriolism
  • Return in advance – call internal judgment for multiple times, and directly return the result of the first judgment to the external receiver
  • Delay calculation / run – avoid repeated execution of the program until the result is really needed

Understand JavaScript function coritization - what is coritization - cloud + community - Tencent cloud coritization technology, which is mainly reflected in the return function in the function. It is to disassemble multivariable functions into multiple functions of single variable (or partial variable) and call them in turn.https://cloud.tencent.com/developer/article/1851152

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Higher order function_Function coritization</title>
</head>
<body>
	<!-- Prepare a "container" -->
	<div id="test"></div>
	
	<!-- introduce react Core library -->
	<script type="text/javascript" src="../js/react.development.js"></script>
	<!-- introduce react-dom,Used to support react operation DOM -->
	<script type="text/javascript" src="../js/react-dom.development.js"></script>
	<!-- introduce babel,Used to jsx Turn into js -->
	<script type="text/javascript" src="../js/babel.min.js"></script>

	<script type="text/babel">
		//#region 
				/* 
					Higher order function: if a function meets any of the following two specifications, the function is a higher order function.
									1.If the parameter received by A function is A function, then A can be called A higher-order function.
									2.If the return value of A function call is still A function, then A can be called A higher-order function.
									Common high-order functions include Promise, setTimeout, arr.map(), etc

					Coriolism of function: the function coding form of receiving parameters for many times and finally unified processing is realized by continuing to return the function through function call. 
						function sum(a){
							return(b)=>{
								return (c)=>{
									return a+b+c
								}
							}
						}
					*/
		//#endregion
		//Create component
		class Login extends React.Component{
			//Initialization status
			state = {
				username:'', //user name
				password:'' //password
			}

			//Save form data to status
			saveFormData = (dataType)=>{
				return (event)=>{
					this.setState({[dataType]:event.target.value})
				}
			}

			//Callback for form submission
			handleSubmit = (event)=>{
				event.preventDefault() //Block form submission
				const {username,password} = this.state
				alert(`The user name you entered is: ${username},The password you entered is: ${password}`)
			}
			render(){
				return(
					<form onSubmit={this.handleSubmit}>
						user name:<input onChange={this.saveFormData('username')} type="text" name="username"/>
						password:<input onChange={this.saveFormData('password')} type="password" name="password"/>
						<button>Sign in</button>
					</form>
				)
			}
		}
		//Rendering Components 
		ReactDOM.render(<Login/>,document.getElementById('test'))
	</script>
</body>
</html>

 2. No coritization:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>2_Implementation of corellization without function</title>
</head>
<body>
	<!-- Prepare a "container" -->
	<div id="test"></div>
	
	<!-- introduce react Core library -->
	<script type="text/javascript" src="../js/react.development.js"></script>
	<!-- introduce react-dom,Used to support react operation DOM -->
	<script type="text/javascript" src="../js/react-dom.development.js"></script>
	<!-- introduce babel,Used to jsx Turn into js -->
	<script type="text/javascript" src="../js/babel.min.js"></script>

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

			//Save form data to status
			saveFormData = (dataType,event)=>{
				this.setState({[dataType]:event.target.value})
			}

			//Callback for form submission
			handleSubmit = (event)=>{
				event.preventDefault() //Block form submission
				const {username,password} = this.state
				alert(`The user name you entered is: ${username},The password you entered is: ${password}`)
			}
			render(){
				return(
					<form onSubmit={this.handleSubmit}>
						user name:<input onChange={event => this.saveFormData('username',event) } type="text" name="username"/>
						password:<input onChange={event => this.saveFormData('password',event) } type="password" name="password"/>
						<button>Sign in</button>
					</form>
				)
			}
		}
		//Rendering Components 
		ReactDOM.render(<Login/>,document.getElementById('test'))
	</script>
</body>
</html>

Topics: Javascript Front-end React