preface

React components can be classified into controlled and uncontrolled (uncontrolled) according to whether they are controlled by React.

In most cases, it is recommended to implement forms using controlled components. In a controlled component, form data is controlled by the component.

The other is uncontrolled components, where the form component is controlled by the DOM itself.

Let’s look at the implementation of these two components separately.

The controlled components

  1. Controlled component passpropsGets its current value and uses the callback function (e.gonChange) Notification change
  2. When the state of the form changes, it is notifiedReactAnd give the state toReactFor example, it can be useduseStatestorage
  3. In a controlled component, the state rendered by the component and itsvalueorcheckedAttribute correspondence
  4. Controlled components are updatedstateThe process of

🌰 A simple example:

export default function App() {
    const [name, setName] = useState(' ');
  
    const handleNameChange = e= > {
      setName(e.target.value);
    }
  
    return (
      <div className="App">
        <div>hello {name}</div>Name:<Input onChange={handleNameChange} />
      </div>
    );
  }
Copy the code

Controlled component – Sample code

There is an input box in the code, the interface shows the content of the input box, with the change of the content of the input box, the upper text changes accordingly.

  • Form componentsInputThe value of the passonChangeThe callback toReactTo deal with
  • ReactGet the value of the form (e.target.value) and save it to a state variablenameIn the
  • The interface displays content by reading component statesname, sonameChange trigger<div>hello {name}</div>Rerendering of

Uncontrolled component

Uncontrolled components store data in the DOM rather than in the component, which is more like traditional HTML form elements.

  1. The value of an uncontrolled component is not bound by the component itselfstateandpropscontrol
  2. Use of uncontrolled componentsreffromDOMGets element data from
export default function App() {
    const eleRef = useRef(null);
    const [submitContent, setSubmitContent] = useState("");
  
    const handleSubmit = () = > {
      // Get the value of the input box by ref
      constcontent = eleRef.current? .value; setSubmitContent(content); };return (
      <div className="App">
        <input ref={eleRef} />
        <Button type="primary" onClick={handleSubmit}>submit</Button>
        <div>{submitContent ?? ""}</div>
      </div>
    );
  }
Copy the code

Uncontrolled component – Sample code

The page contains an input box and a button. The reference of the input box is obtained through ref. After changing the input content, click Submit and the page will display the input box content.

  • ReactthroughrefTo obtaininputThe value of the element
  • inputValue changed by user, click submit button, inhandleSubmitThrough therefTo obtainDOMElement to read the value of the input box
  • Changes to the input box are not controlled by the component, but byrefGet, that is, directly inDOMReads the

conclusion

  1. ReactComponents are classified into controlled components and uncontrolled components
  2. Two key points of controlled components:
    • The component’svalueProperties andReactState binding in
    • Declared in the componentonChangeThe event processingvalueThe change of the
  3. Uncontrolled components are more traditionalHTMLForm elements, data stored inDOMIn, rather than inside the component, the way to get data is throughrefreference
  4. Some suggestions:
    • Use controlled components whenever possible
    • Controlled components hand over stateReactProcessing, which can be any element, not just a form element
    • For pages with a large number of form elements, it is wise to use uncontrolled components when controlled components can make the program cumbersome
    • In a controlled component, the data flow is one-way (stateIs a source of change), and therefore is changingstateShould be usedsetStateInstead of forcing an assignment
    • RefsCannot be used for functional components because functional components have no instances
    • Within functional components, yes is availableRefsthe

Refer to the link

Controlled components and uncontrolled components

What are React controlled components and uncontrolled components?

Controlled vs Uncontrolled Components in React

React Controlled Components, the Hooks Way