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

Implementation code of using select to select elements in Vue+Openlayer

Effect picture: Implementation code: <template...

What magical uses does CSS filter have

background Basic Concepts CSS filter property app...

Native js drag and drop function to create a slider example code

Drag and drop is a common function in the front e...

Analysis of the process of deploying pure HTML files in Tomcat and WebLogic

1. First, the pure HTML file must have an entry i...

Detailed explanation of DOM style setting in four react components

1. Inline styles To add inline styles to the virt...

Detailed explanation of how to adjust Linux command history

The bash history command in Linux system helps to...

A detailed discussion of MySQL deadlock and logs

Recently, several data anomalies have occurred in...

Native JS to implement drag position preview

This article shares with you a small Demo that ad...

HTML head tag meta to achieve refresh redirection

Copy code The code is as follows: <html> &l...

MYSQL A question about using character functions to filter data

Problem description: structure: test has two fiel...

Some conclusions on the design of portal website focus pictures

Focus images are a way of presenting content that ...

MySQL: Data Integrity

Data integrity is divided into: entity integrity,...

Detailed explanation of tinyMCE usage and experience

Detailed explanation of tinyMCE usage initializat...