Home Web Front-end JS Tutorial Detailed explanation of react controlled components and uncontrolled components

Detailed explanation of react controlled components and uncontrolled components

Feb 11, 2018 am 09:46 AM
react components

We all know that there are many web components that can be changed by user interaction, such as: , component that maintains the value in its own state cannot be modified from the outside;

2. An component that sets the value through props The component can only be updated via external control.

I recently encountered a problem when using a react-based ant-design UI component produced by Ant Financial. When editing the page, the input box will display the data before saving, but using defaultValue does not work. , the input box is always empty instead of the specific incoming value. The code related to the text box in the specific editing page is as follows:


    ... //render方法上面的内容省略
 <FormItem
   label="问题描述:"
   hasFeedback
   {...props.formItemLayout}
 >
  <Input type="textarea" defaultValue={props.value}/>
</FormItem>
      //render下面的内容省略
      ...
Copy after login

After passing value props to the component to which the code segment belongs, the default value in the text box is always empty, because In the state where the page is located, the initial value of the state corresponding to value is empty. As a result, after subsequent asynchronous requests are successful, the value in the state corresponding to value is changed and the value is still displayed as empty.

Google the specific reason. It turns out that once the defaultValue in the form component of React is passed, subsequent changes to the defaultValue will have no effect and will be ignored.

Specifically, this is a react uncontrolled component. Its state is controlled within the input react and is not controlled by the caller. This can be achieved using controlled components.

Let’s talk about this controlled component and uncontrolled component. They are all based on react’s form component elements. For details, you can also refer to the react official website for this introduction

Controlled component

Formally speaking, a controlled component is to add a value attribute to a form component; an uncontrolled component is a component that does not add a value attribute; a controlled component The form is as follows:


render: function() {
  return <input type="text" value="Hello!" />;
 }
Copy after login

The form component element with added value attribute will not maintain its own state internally. Once the value value of the component is set to a specific value, It is always this value, so the caller needs to control the change of component value.

This way of writing brings a problem: any value entered by the user will not work in the user interaction of the rendered input component, and the value in the input box is always Hello!. This is inconsistent with the behavior of input in HTML.

For this reason, in order to control the component, you need to be able to control the value of the input component. You need to use its internal state, that is, a state must be maintained inside the component to cooperate with the onChange and setState methods of the input component. Complete the control of components; for example, the above form can be encapsulated into an inputItem component, which maintains a state internally. The specific code is as follows:


 export default class InputItem extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      value: ""
    }
  }

  componentWillReceiveProps(nextProps){
    this.setState({
      value: nextProps.value
    })
  }

  _onChange(evt){
    this.setState({
      value: evt.target.value
    })
  }

  render(){
    return (
      <input type="text" 
        value={this.state.value} 
        onChange={this._onChange.bind(this)}/>
    );
  }
}
Copy after login

In this way, it can be externally like The InputItem component is called as follows:


<InputItem value={this.state.userName} />
Copy after login

In this way, you can control the Input component of react. In fact, you need to use the stateful component of react to complete it, because the stateful component can Maintain state internally.

Uncontrolled components

In terms of expression, form component elements that do not add a value attribute in react are uncontrolled components. The expression is as follows:


<input type="text" />
Copy after login

The uncontrolled component maintains its own state internally during the underlying implementation; this shows that any value input by the user can be reflected on the elements.

Summary

When using react component, you will encounter controlled components or uncontrolled components; at present, react components recommend using stateless components, but using this There is no big problem when using uncontrolled components to implement react components. If you need to control controlled elements, there will be problems, as shown in:

`Controlled components` need to actively maintain an internal state Stateful, while `stateless component` does not need to maintain the state of the component, and the two conflict.
So, controlled elements cannot be created using stateless components.

In view of the characteristics of controlled components and uncontrolled components, the application places of the two are also different, mainly in:

  1. Controlled elements are generally used in Situations where its initial value needs to be set dynamically; for example, when editing some form information, the input form element needs to initially display a certain value returned by the server and then edit it.

  2. Uncontrolled elements are generally used when there is no dynamic initial value information; for example, when creating information in a form, the input form elements have no initial value and require user input

Related recommendations:

Detailed explanation of React controlled components and uncontrolled components

The above is the detailed content of Detailed explanation of react controlled components and uncontrolled components. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to install the Windows 10 old version component DirectPlay How to install the Windows 10 old version component DirectPlay Dec 28, 2023 pm 03:43 PM

Many users always encounter some problems when playing some games on win10, such as screen freezes and blurred screens. At this time, we can solve the problem by turning on the directplay function, and the operation method of the function is also Very simple. How to install directplay, the old component of win10 1. Enter "Control Panel" in the search box and open it 2. Select large icons as the viewing method 3. Find "Programs and Features" 4. Click on the left to enable or turn off win functions 5. Select the old version here Just check the box

PHP, Vue and React: How to choose the most suitable front-end framework? PHP, Vue and React: How to choose the most suitable front-end framework? Mar 15, 2024 pm 05:48 PM

PHP, Vue and React: How to choose the most suitable front-end framework? With the continuous development of Internet technology, front-end frameworks play a vital role in Web development. PHP, Vue and React are three representative front-end frameworks, each with its own unique characteristics and advantages. When choosing which front-end framework to use, developers need to make an informed decision based on project needs, team skills, and personal preferences. This article will compare the characteristics and uses of the three front-end frameworks PHP, Vue and React.

Angular components and their display properties: understanding non-block default values Angular components and their display properties: understanding non-block default values Mar 15, 2024 pm 04:51 PM

The default display behavior for components in the Angular framework is not for block-level elements. This design choice promotes encapsulation of component styles and encourages developers to consciously define how each component is displayed. By explicitly setting the CSS property display, the display of Angular components can be fully controlled to achieve the desired layout and responsiveness.

How to open the settings of the old version of win10 components How to open the settings of the old version of win10 components Dec 22, 2023 am 08:45 AM

Win10 old version components need to be turned on by users themselves in the settings, because many components are usually closed by default. First we need to enter the settings. The operation is very simple. Just follow the steps below. Where are the win10 old version components? Open 1. Click Start, then click "Win System" 2. Click to enter the Control Panel 3. Then click the program below 4. Click "Enable or turn off Win functions" 5. Here you can choose what you want to open

Integration of Java framework and front-end React framework Integration of Java framework and front-end React framework Jun 01, 2024 pm 03:16 PM

Integration of Java framework and React framework: Steps: Set up the back-end Java framework. Create project structure. Configure build tools. Create React applications. Write REST API endpoints. Configure the communication mechanism. Practical case (SpringBoot+React): Java code: Define RESTfulAPI controller. React code: Get and display the data returned by the API.

Vue component development: implementation method of progress bar component Vue component development: implementation method of progress bar component Nov 24, 2023 am 08:56 AM

Vue component development: Progress bar component implementation method Preface: In Web development, the progress bar is a common UI component, often used to display the progress of operations in scenarios such as data requests, file uploads, and form submissions. In Vue.js, we can easily implement a progress bar component by customizing components. This article will introduce an implementation method and provide specific code examples. I hope it will be helpful to Vue.js beginners. Component structure and style First, we need to define the basic structure and style of the progress bar component.

Vue component practice: paging component development Vue component practice: paging component development Nov 24, 2023 am 08:56 AM

Vue component practice: Introduction to paging component development In web applications, the paging function is an essential component. A good paging component should be simple and clear in presentation, rich in functions, and easy to integrate and use. In this article, we will introduce how to use the Vue.js framework to develop a highly customizable paging component. We will explain in detail how to develop using Vue components through code examples. Technology stack Vue.js2.xJavaScript (ES6) HTML5 and CSS3 development environment

Vue.js vs. React: Project-Specific Considerations Vue.js vs. React: Project-Specific Considerations Apr 09, 2025 am 12:01 AM

Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

See all articles