Come and join us!

“The Newbies of Little and Hill” provides technical information and a series of basic articles for front-end developers. For a better user experience, please move to our official website of Xiaoheshan beginners (https://xhs-rookies.com/) to learn, timely access to the latest articles.

“Code tailor”, if you are interested in our articles or would like to make some suggestions, please follow our official account “newbies of Xiaoheshan” at WeChat, and contact us. You can also view our articles on WeChat. Every suggestion or agreement is a great encouragement to us!

preface

In this section we will introduce the concepts of controlled and uncontrolled components in React and their use.

This article will introduce you to the following:

  • What is a controlled/uncontrolled component
  • The controlled components
  • Uncontrolled component

What is a controlled/uncontrolled component

In HTML, form elements such as ,

We can combine these two forms by making React state the “Single Data Source Principle.” Then the React component that renders the form can also control the behavior after user input.

In this form, input form elements whose values are controlled by React are called “controlled components.”

Instead, values are not controlled by React, the component inputs itself, decrements, etc., and the element becomes an uncontrolled component.

For more information on when to use controlled components and when to use uncontrolled components, see this article:

Controlled and uncontrolled form inputs in React don’t have to be complicated – Gosha Arinich (goshakkk.name)

The controlled components

Understanding Controlled Components

Default form submission method

HTML form elements are different from other DOM elements in React because form elements naturally retain some internal state.

For example, this pure HTML form takes a single name:

The < form > < label > name: < input type = "text" name = "name" / > < / label > < input type = "submit" value = "submit" / > < / form >

This form behaves like an HTML form by default, and the browser opens a new page when the user submits the form. If you want to keep this behavior in React, it works.

But most of the time, we’ll let the React component manage the data and click to submit it and trigger a new page.

This refers to “controlled components”.

The controlled component submits the form

In HTML, form elements such as ,

In React, mutable states are usually stored in the component’s state property and can only be updated using setState().

  • We combine the two to makeReactstateBe the “Unique Data Source”;
  • Render FormReactThe component also controls what happens to the form during user input;
  • beReactForm input elements that control values in this way are called “controlled components”;

For example, if we wanted the previous example to print out the name when submitting, we could write the form as a controlled component:

class App extends PureComponent { constructor(props) { super(props) this.state = { username: "', } } render() { const { username } = this.state return ( <div> <form onSubmit={(e) => this.handleSubmit(e)}> <label HtmlFor ="username"> <input type="text" id="username" onChange={(e) => this.handleUsernameChange(e)} value={username} /> </label> <input Type ="submit" value=" submit" /> </form> </div>)} handleUsernameChange(event) {this.setState({username: event.target.value, }) } handleSubmit(event) { console.log(this.state.username) event.preventDefault() } }

Since the value attribute is set on the form element, the value displayed will always be this.state.value, making the state of React the only data source.

Because HandleUsernameChange executes and updates the React state each time it presses a button, the displayed value will be updated as the user enters it.

Uncontrolled component

Ref creation and use

In the React development model, direct manipulation of DOM nativeness is not usually required or recommended, but there are some special cases where you do need to acquire the DOM for certain operations:

  • Manage focus, text selection or media playback.
  • Trigger a forced animation.
  • Integration with third partiesDOMLibrary.

If we use an uncontrolled component, we have a problem, how do we get the data for that component, so we can use Refs to get the data for that component, and then we can get the data for that component. So let’s briefly describe what Refs are.

Note:Of course, there are other ways to get component content, such as variable promotion to parent component unified management, event listening.

How to create a ref

How do you create refs to get the corresponding DOM? There are currently three ways:

  • Way one: pass in a string

Returns the corresponding element in the string format passed by this.refs.

  • Method two: pass in an object

The object is created by React.createRef(); One of the current properties is the corresponding element in the created object.

  • Approach three: pass in a function

This function calls back when the DOM is mounted. This function passes in an element object that you can keep for yourself. When using, directly get the previously saved element object;

Code walkthrough:

class App extends PureComponent { constructor(props) { super(props) this.titleRef = createRef() this.titleEl = null } render() { return ( <div> <h2 ref="title">String Ref</h2> <h2 ref={this.titleRef}>Hello Create Ref</h2> <h2 }>Callback ref </h2> <button onClick={(e) => this.changeText()}> </button> < / div >)} changeText () {this. Refs. Title. InnerHTML = 'hello, little mount and rookies' enclosing titleRef. Current. The innerHTML =' hello, little mount and rookies' This. titleel. innerHTML = 'Hello, noviciers of Owayama'}}

The type of the Ref node

The ref value varies depending on the type of the node:

  • whenrefProperty is used toHTMLElement is used in the constructorReact.createRef()To create therefReceive the underlyingDOMThe element serves as thecurrentProperties;
  • whenrefProperty is used for customizationclassComponent,refObject receives a mount instance of the component as itscurrentProperties;
  • You can’t use ref attributes on function components because they have no instances;

Here we demonstrate that ref refers to a class component object:

class Counter extends PureComponent { constructor(props) { super(props) this.state = { counter: 0,}} render() {return (<div> <h2>) {return (<div> <h2>); {this.state.counter}</h2> <button onClick={(e) => this.increment()}>+1</button> </div> ) } increment() { this.setState({  counter: this.state.counter + 1, }) } } class App extends PureComponent { constructor(props) { super(props) this.counterRef = createRef() } render() { return ( <div> <Counter ref={this.counterRef} /> <button onClick={(e) => this.increment()}>app +1</button> </div> ) } increment() { this.counterRef.current.increment() } }

Functional components do not have instances, so they cannot be retrieved via ref, but sometimes we might want to retrieve a DOM element in a functional component by using React.forwardRef. We will also see how refs are used in hooks later.

Recognize uncontrolled components

React recommends using controlled components to process form data in most cases:

  • In a controlled component, the form data is composed ofReactComponents to manage;
  • Another alternative is to use uncontrolled components, where the form data is handed over toDOMNode to process;

If we want to use data from an uncontrolled component, we need to use Ref to get form data from the DOM node.

Let’s do a simple exercise:

  • useref In order to getinputElements;
  • Commonly used in uncontrolled componentsdefaultValueTo set the default value;
class App extends PureComponent { constructor(props) { super(props) this.usernameRef = createRef() } render() { return ( <div> <form onSubmit={(e) => this.handlesubmit (e)}> <label htmlFor=""> <input defaultValue="username" type="text" name="username" ref={this.usernameRef} /> </label> <input type="submit" Value =" submit "/ bb0 </form> </div>)} handleSubmit(event) {event.preventDefault(); console.log(this.usernameRef.current.value) } }

and support defaultChecked,

Next day forecast

In this section, we learned about controlled and uncontrolled components in React. In the next chapter, we will continue to learn about higher-order components in React and how they complement each other.