In React, a controlled component refers to a component that updates the current value through a callback function; the React component that renders the form also controls the operations that occur on the form during user input. Whenever the state of the form changes, it will be written Into the state of the component, this kind of component is called a controlled component in React.
The operating environment of this tutorial: Windows 10 system, react version 17.0.1, Dell G3 computer.
The React component that renders the form also controls what happens to the form during user input. Form input elements whose values are controlled by React in this way are called "controlled components".
Some netizens explained this: In React, whenever the state of the form changes, it will be written to the state of the component. This type of component is called a controlled component in React.
Update process for controlled components:
1. You can set the default value of the form in the initial state
2. Whenever the value of the form changes, call the onChange event handler.
3. The event processor gets the changed state through the event object e and changes the state;
4. setState triggers view update and completes the update of form component values.
Controlled components update the current value through callback functions, such as OnChange. The parent component controls and manages its state through callback functions and passes new values to it as properties. Controlled components are also called "dumb components".
const { useState } from 'react'; function Controlled () { const [email, setEmail] = useState(); const handleInput = (e) => setEmail(e.target.value); return <input type="text" value={email} onChange={handleInput} />;}Expand your knowledge:
What are uncontrolled components?
Uncontrolled components are components that store their own state internally and can use ref to query the DOM to find their current value when needed. Kind of like traditional HTML. Most native React form components support controlled and uncontrolled:
const { useRef } from 'react';function Example () { const inputRef = useRef(null); return <input type="text" defaultValue="bar" ref={inputRef} />}4 What are the differences between them?
In controlled components, form data is handled by React components. In uncontrolled components, the form data is handled by the DOM itself.
For controlled components, component state must be used. For uncontrolled components, the use of state is completely optional, but Refs must be used within them.
For controlled components we can validate on input but not for uncontrolled components.