A brief analysis of controlled and uncontrolled components in React

A brief analysis of controlled and uncontrolled components in React

Uncontrolled components

The form data is handled by the DOM itself. That is, it is not controlled by setState(), and is similar to traditional HTML form input. The input value shows the latest value (using ref to get the form value from DOM)

1. Uncontrolled components

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

<!--Introduce react core library-->
<script src="../js/react.development.js"></script>
<!--Introduce react-dom to support react operation dom-->
<script src="../js/react-dom.development.js"></script>
<!--Introduce babel to convert jsx to js-->
<script src="../js/babel.min.js"></script>
<!--Introduce prop-types to restrict component tag properties-->
<script src="../js/prop-types.js"></script>

<script type="text/babel">
    class Login extends React.Component {
        myRef1 = React.createRef();
        myRef2 = React.createRef();
        handleSubmit = (event) => {
            event.preventDefault() // Prevent form submission const username = this.myRef1.current
            const password = this.myRef2.current
            alert(`The username you entered is: ${username.value}, the password you entered is: ${password.value}`)
        }
        render() {
            return (
                <form onSubmit={this.handleSubmit}>
                    Username: <input ref={this.myRef1} type="text"/> &nbsp;
                    Password: <input ref={this.myRef2} type="text"/> &nbsp;
                    <button>Login</button>
                </form>
            )
        }
    }
    ReactDOM.render(<Login/>,document.getElementById('test'))
</script>
</body>
</html>

Controlled Components

In HTML, the values ​​of tags <input>, <textarea>, and <select> are usually updated based on user input. In React, mutable state is typically stored in a component's state property and can only be updated using setState() . The React component that renders the form also controls what happens to that form upon subsequent user input. This way, input form elements controlled by React change their values, which is called a "controlled component."

2. Controlled components (controlled)

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

<!--Introduce react core library-->
<script src="../js/react.development.js"></script>
<!--Introduce react-dom to support react operation dom-->
<script src="../js/react-dom.development.js"></script>
<!--Introduce babel to convert jsx to js-->
<script src="../js/babel.min.js"></script>
<!--Introduce prop-types to restrict component tag properties-->
<script src="../js/prop-types.js"></script>

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

        // Save the username to the state saveUsername = (e) => {
            this.setState({username: e.target.value})
        }

        // Save the password to the state savePassword = (e) => {
            this.setState({password: e.target.value})
        }

        handleSubmit = (e) => {
            e.preventDefault() // Prevent form submission const {username,password} = this.state
            alert(`The username you entered is: ${username}, the password you entered is: ${password}`)
        }
        render() {
            // onChange changes return (
                <form onSubmit={this.handleSubmit}>
                    Username: <input onChange={this.saveUsername} type="text"/> &nbsp;
                    Password: <input onChange={this.savePassword} type="text"/> &nbsp;
                    <button>Login</button>
                </form>
            )
        }
    }
    ReactDOM.render(<Login/>,document.getElementById('test'))
</script>
</body>
</html> 

insert image description here

Notice

Generally, controlled components are used more frequently because ref is used multiple times in uncontrolled components, and the official documentation says "do not overuse ref". Using it too many times will cause efficiency problems.

in conclusion

Both controlled and uncontrolled elements have their advantages and the choice depends on the specific situation. If the form is very simple in terms of UI feedback, it is perfectly fine to control the ref, i.e. use an uncontrolled component.

feature Uncontrolled controlled
One-time retrieval (e.g. form submission) yes yes
Timely verification no yes
Conditionally disabling the submit button no yes
Execute input format no yes
Several inputs for one data no yes
Dynamic Input no yes

The above is a brief analysis of the details of controlled components and uncontrolled components in React. For more information about controlled and uncontrolled components in React, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • A brief discussion on react controlled components and uncontrolled components (summary)
  • A brief discussion on controlled and uncontrolled components in React deep programming
  • React learning controlled components and data sharing example analysis
  • React uses Hooks to simplify state binding of controlled components

<<:  A record of a Linux server intrusion emergency response (summary)

>>:  MySQL incremental backup and breakpoint recovery script example

Recommend

Hide div in HTML Hide table TABLE or DIV content css style

I solved a problem tonight that has been botherin...

Several ways of running in the background of Linux (summary)

1. nohup Run the program in a way that ignores th...

Implementation of Grid common layout

No gaps on both sides, gaps between each column w...

JavaScript to achieve a simple carousel effect

What is a carousel? Carousel: In a module or wind...

How to prompt and open hyperlink a

<br />The countless information on the Inter...

A brief discussion on three methods of asynchronous replication in MySQL 8.0

In this experiment, we configure MySQL standard a...

CocosCreator implements skill cooling effect

CocosCreator realizes skill CD effect There are s...

Getting Started Guide to MySQL Sharding

Preface Relational databases are more likely to b...

Express implements login verification

This article example shares the specific code for...

8 powerful techniques for HTML web page creation

<br />Although there are many web page creat...

Are the value ranges of int(3) and int(10) the same in mysql

Table of contents Question: answer: Reality: Know...

How to install redis5.0.3 in docker

1. Pull the official 5.0.3 image [root@localhost ...

6 Ways to Elegantly Handle Objects in JavaScript

Table of contents Preface 1. Object.freeze() 2. O...

How to install Solr 8.6.2 in Docker and configure the Chinese word segmenter

1. Environment version Docker version 19.03.12 ce...

MySQL series: Basic concepts of MySQL relational database

Table of contents 1. Basic Concepts 2. Developmen...