受控组件与状态
使用 React 的受控组件模式管理表单输入值,实现可预测的行为。
受控组件与状态 是 CoddyKit 上的免费 Next.js 15 Fullstack Web Apps 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Next.js 15 Fullstack Web Apps 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Next.js 15 Fullstack Web Apps 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Forms: User Interaction Hub
Forms are essential for almost any web application! They allow users to input information, make choices, and interact with your app.
Think about login screens, search bars, feedback forms, or even shopping cart quantity selectors – all rely on forms.
Uncontrolled Inputs: A Quick Look
In plain HTML, input elements manage their own state. When you type into an <input>, its value updates internally.
In React, these are called uncontrolled components. While simple for static forms, they can be tricky to integrate with React's dynamic UI updates and state management.
Meet Controlled Components
Controlled components are input elements whose values are controlled by React state. Instead of the DOM managing the input's value, your React component's state becomes the 'single source of truth'.
This gives you full control over the form data, making it predictable and easier to manage.
The Core: `value` & `onChange`
Two props are key to controlled components:
value: Sets the current displayed value of the input. It should always come from your component's state.onChange: A function that gets called whenever the input's value changes (e.g., user types). This function updates your component's state.
Controlled Text Input in Action
Let's see a basic controlled text input. We use useState to hold the input's value and update it with onChange.
Try typing in the input below:
import React, { useState } from 'react';
function App() {
const [name, setName] = useState('');
const handleChange = (event) => {
setName(event.target.value);
};
return (
<div>
<label>Your Name:</label>
<input
type="text"
value={name}
onChange={handleChange}
/>
<p>Hello, {name || 'stranger'}!</p>
</div>
);
}
State is the Single Source of Truth
Here's the flow for a controlled input:
- The input's
valueprop is set by React state (e.g.,name). - User types a character.
- The
onChangeevent fires, callinghandleChange. handleChangeupdates the state (setName).- React re-renders the component.
- The input's
valueprop is now updated with the new state, displaying the typed character.
Other Controlled Elements
The same value and onChange pattern applies to other form elements like <textarea> and <select>.
For <select>, the value prop is set on the <select> tag itself, not on individual <option> tags.
import React, { useState } from 'react';
function App() {
const [feedback, setFeedback] = useState('');
const [fruit, setFruit] = useState('apple');
return (
<div>
<label>Your Feedback:</label>
<textarea
value={feedback}
onChange={(e) => setFeedback(e.target.value)}
rows="3"
/>
<p>Feedback: {feedback}</p>
<label>Favorite Fruit:</label>
<select
value={fruit}
onChange={(e) => setFruit(e.target.value)}
>
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="orange">Orange</option>
</select>
<p>Selected: {fruit}</p>
</div>
);
}
Why Control Matters
Controlling your form inputs provides many benefits:
- Instant Validation: Validate input as the user types.
- Conditional Logic: Enable/disable buttons based on input state.
- Formatted Input: Automatically format phone numbers or currencies.
- Easy State Access: Always know the current value of any input.
- Predictable Behavior: Your UI always reflects your application's state.
Managing Many Inputs
For forms with multiple inputs, you can use a single state object and a generic onChange handler. The name attribute of the input helps identify which state property to update.
import React, { useState } from 'react';
function App() {
const [formData, setFormData] = useState({
username: '',
email: ''
});
const handleChange = (event) => {
const { name, value } = event.target;
setFormData(prevData => ({ ...prevData, [name]: value }));
};
return (
<form>
<label>Username:</label>
<input
type="text"
name="username"
value={formData.username}
onChange={handleChange}
/>
<label>Email:</label>
<input
type="email"
name="email"
value={formData.email}
onChange={handleChange}
/>
<p>User: {formData.username}, Email: {formData.email}</p>
</form>
);
}
Controlled Input Challenge
Which of the following are key characteristics of a controlled component in React?
Recap: Controlled & Predictable
You've learned about controlled components!
- They link input values directly to React state.
- They use the
valueprop for display and anonChangehandler to update state. - This pattern provides full control, enabling features like instant validation and predictable behavior.
- It applies to
<input>,<textarea>, and<select>elements.
Mastering controlled components is a crucial step for building robust forms in Next.js applications!
常见问题解答
「受控组件与状态」课时是免费的吗?
是的 — 「受控组件与状态」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Next.js 15 Fullstack Web Apps 课程的其余内容,请升级到 CoddyKit PRO。 Next.js 15 Fullstack Web Apps 课程共包含 4 节课。
「受控组件与状态」这节课中我会学到什么?
使用 React 的受控组件模式管理表单输入值,实现可预测的行为。 你通过在浏览器中直接运行的动手代码来练习 Next.js 15 Fullstack Web Apps,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Next.js 15 Fullstack Web Apps 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Next.js 15 Fullstack Web Apps 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「受控组件与状态」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Next.js 15 Fullstack Web Apps 课中编写并运行代码吗?
能。每节 Next.js 15 Fullstack Web Apps 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。