8
头图

join us!

160ebbe52063a3 " , provides technical related information and series of basic articles for front-end developers. For a better user experience, please move to our official website novices (160ebbe52063ad https://xhs-rookies.com/ ) to learn and get the latest articles in time.

"Code tailor" , if you are interested in our article or want to make some suggestions, follow "Novices of Xiaohe Mountain" public account, contact us, you can also watch it on WeChat Our article. Every suggestion or approval is a great encouragement to us!

Preface

In this section, we will introduce the concept and use of controlled and uncontrolled components in React

This article will introduce you to the following:

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

What is a controlled component/uncontrolled component

In HTML , form elements such as <input> , <textarea> and <select> form elements usually maintain their own state and are updated according to user input. In React , the variable state is generally stored in the state attribute of the component, and can only be updated setState()

We can React of state a "single data source principle". Then the React component that renders the form can also control its behavior after user input.

In this form, React called "controlled component".

So on the contrary, the value is not controlled by React , the component itself enters, decreases, etc., and the element becomes an uncontrolled component.

For when to use controlled components and when to use uncontrolled components, you can check this article:

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

Controlled component

Know the controlled components

Default form submission method

HTML form elements and React in other DOM elements is different, because the form elements naturally retains some internal state.

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

<form>
  <label>
    名字:
    <input type="text" name="name" />
  </label>
  <input type="submit" value="提交" />
</form>

This form is HTML form. When the user submits this form, the browser will open a new page. If you want this behavior to be maintained in React

But in most cases, we will let the React component manage these data, and click to submit the data and trigger the operation of opening a new page.

This uses the "controlled component ( controlled components )".

Controlled component submission form

In HTML , form elements (such as <input> , <textarea> and <select> ) and other form elements usually maintain their own state and update them based on user input.

In React , the variable state ( mutable state ) is usually stored in the state attribute of the component, and can only be updated setState()

  • We combine the two to make React of state the "only data source";
  • React component that renders the form also controls the operation of the form during user input;
  • The form input element whose value is controlled by React in this way is called "controlled component";

For example, if we want the previous example to print the name when submitted, we can 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="提交" />
        </form>
      </div>
    )
  }

  handleUsernameChange(event) {
    this.setState({
      username: event.target.value,
    })
  }

  handleSubmit(event) {
    console.log(this.state.username)
    event.preventDefault()
  }
}

value attribute is set on the form element, the displayed value will always be this.state.value , which makes React's state the only data source.

Since handleUsernameChange React of state every time a key is pressed, the displayed value will be updated with user input.

Uncontrolled components

Ref creation and use

In React , it is usually not necessary or recommended to directly operate DOM , but in some special cases, it is necessary to obtain DOM for certain operations:

  • Manage focus, text selection or media playback.
  • Trigger forced animation.
  • Integrate third-party DOM library.

If we use an uncontrolled component here, there will be a problem, how to get the data of the component, here we can use Refs to get the component, and then we can get the data of the component. So we first briefly describe the content of Refs

Note: Of course, there are other methods to obtain component content, such as: variables are promoted to the parent component for unified management and event monitoring.

How to create ref

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

  • Method 1: Pass in a string

When in use, obtain the corresponding element through the string

  • Method 2: Pass in an object

The object is React.createRef() method; when using the created object, one of the current attributes is the corresponding element;

  • Method 3: Pass in a function

This function will DOM is mounted. This function will pass in an element object, which we can save by ourselves; when using it, we can 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 ref={(element) => (this.titleEl = element)}>Callback Ref</h2>

        <button onClick={(e) => this.changeText()}>改变文本</button>
      </div>
    )
  }

  changeText() {
    this.refs.title.innerHTML = '你好啊,小和山的菜鸟们'
    this.titleRef.current.innerHTML = '你好啊,小和山的菜鸟们'
    this.titleEl.innerHTML = '你好啊,小和山的菜鸟们'
  }
}

Ref node type

ref varies according to the type of node:

  • When the ref attribute is used for the HTML element, the React.createRef() created with ref receives the underlying DOM element as its current attribute;
  • When the ref attribute is used to customize the class component, the ref object receives the mounted instance of the component as its current attribute;
  • You cannot use ref attribute on function components because they have no instances;

Here we demonstrate that ref references a class component object:

class Counter extends PureComponent {
  constructor(props) {
    super(props)

    this.state = {
      counter: 0,
    }
  }

  render() {
    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 have no instances, so they cannot be obtained through ref , but sometimes, we may want to obtain a certain DOM element in the functional component. At this time, we can pass React.forwardRef , and we will learn hooks How to use ref .

Identify uncontrolled components

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

  • In a controlled component, the form data is managed by the React component;
  • Another alternative is to use uncontrolled components, in which case the form data will be processed by the DOM

If you want to use the data in the uncontrolled component, then we need to use Ref to get the form data from the DOM

Let's carry out a simple exercise:

  • Use ref to get the input element;
  • In uncontrolled components, defaultValue is usually used to 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="提交" />
        </form>
      </div>
    )
  }

  handleSubmit(event) {
    event.preventDefault()
    console.log(this.usernameRef.current.value)
  }
}

Similarly, <input type="checkbox"> and <input type="radio"> support defaultChecked , and <select> and <textarea> support defaultValue .

Preview of the next section

In this section, we have studied the React central control components and uncontrolled components. In the next chapter, we will continue to learn React middle and high-end components and component supplementary content, so stay tuned!


小和山的菜鸟们
377 声望2.1k 粉丝

每日进步的菜鸟,分享前端学习手册,和有心学习前端技术的小伙伴们互相探讨,一同成长。