Simple understanding of react controlled components

Controlled Components

<input
    type="text"
    value={this.state.value}
    onChange={(e) => {
        this.setState({
            value: e.target.value.toUpperCase(),
        });
    }}
/>

<input>Or <select>bind a change event; whenever the state of the form changes, it will be written to the state of the component, which is called a controlled component in React; in a controlled component, the state rendered by the component Corresponds to its value or checked prop. React eliminates the local state of the component in this way, and the entire state of the application is controllable. React officials also recommend the use of controlled form components. process:

  • 1. The default value of the form can be set through the initial state;
  • 2. Whenever the value of the form changes, call the onChange event handler;
  • 3. The event handler gets the changed state by synthesizing the event object e, and updates the state of the application.
  • 4.setState triggers the re-rendering of the view, and the completed form component is worth updating

Data in react flows one-way. From the example, we can see that the data of the form comes from the state of the component and is passed in through props, which is also called one-way data binding. Then, we process it through the onChange event The browser writes the new form data back to the state, completing the two-way data binding.

uncontrolled components

  • If a form component does not have value props (checked props for radio buttons and check buttons), it can be called an uncontrolled component;
  • Use defaultValue and defaultChecked to represent the default state of the component;
  • Set the default value of the component through defaultValue and defaultChecked, it will only be rendered once and will not work in subsequent renderings
import React, { Component } from 'react';

class UnControlled extends Component {
    handleSubmit = (e) => {
        console.log(e);
        e.preventDefault();
        console.log(this.name.value);
    }
    render() {
        return (
            <form onSubmit={this.handleSubmit}>
                <input type="text" ref={i => this.name = i} defaultValue="BeiJing" />
                <button type="submit">Submit</button>
            </form>
        );
    }
}

export default UnControlled;

Comparing controlled and uncontrolled components

Convert the entered letters to uppercase

<input
    type="text"
    value={this.state.value}
    onChange={(e) => {
        this.setState({
            value: e.target.value.toUpperCase(),
        });
    }}
/>

Display the typed letters directly

<input
    type="text"
    defaultValue={this.state.value}
    onChange={(e) => {
        this.setState({
            value: e.target.value.toUpperCase(),
        });
    }}
/>

1. Performance problems

In the controlled component, every time the value of the form changes, the onChange event handler will be called once, which will indeed lead to performance loss. Although the usage fee-controlled component will not have these problems, it is still not recommended to use it. For uncontrolled components, this problem can be achieved by means of Flux/Redux application architecture to achieve the purpose of unifying component state.

2. Do you need event binding?

Using controlled components requires binding a change event to each component and defining an event handler to synchronize the form values ​​with the state of the component. This is a necessary condition. Of course, in some cases, an event handler can be used to handle multiple form fields

import React, { Component } from 'react';

class Controlled extends Component {
    constructor(...args) {
        super(...args);
        this.state = {
            name: 'xingxing',
            age: 18,
        };
    }
    handleChange = (name, e) => {
        const { value } = e.target;
        this.setState({
            [name]: value,
        });
    }
    render() {
        const { name, age } = this.state;
        return (
            <div>
                <input type="text" value={name} onChange={this.handleChange.bind(this, 'name')} />
                <input type="text" value={age} onChange={this.handleChange.bind(this, 'age',)} />
            </div>
        );
    }
}

export default Controlled;

Several important properties of form components

1. Status attribute

React's form component provides several important properties to display the state of the component

  • value: input components of type text, textarea components and select components all use the value prop to display the state of the application
  • checked: A component of type radio or checkbox displays the state of the application with the help of a selected prop whose value is of type boolean
  • selected: This attribute can act on the option below the select component. React does not recommend this way to represent the state. Instead, it is recommended to use the value method on the select component.

2. Event properties

The onChange event property is fired when the state property changes. The change event in a controlled component is more similar to the input event provided in the HTML DOM;

Article reprinted from: https://segmentfault.com/a/1190000012404114

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324627175&siteId=291194637