添加交互性
屏幕上的一些内容会根据用户输入进行更新。例如,点击图片图库会切换活动图片。在 React 中,随时间变化的数据称为状态。你可以将状态添加到任何组件中,并根据需要进行更新。在本章中,你将学习如何编写能够处理交互、更新其状态并随时间显示不同输出的组件。
🌐 Some things on the screen update in response to user input. For example, clicking an image gallery switches the active image. In React, data that changes over time is called state. You can add state to any component, and update it as needed. In this chapter, you’ll learn how to write components that handle interactions, update their state, and display different output over time.
在此章节中
响应事件
🌐 Responding to events
React 让你可以向你的 JSX 添加事件处理程序。事件处理程序是你自己的函数,当用户进行交互操作时(如点击、悬停、聚焦表单输入等)会触发这些函数。
🌐 React lets you add event handlers to your JSX. Event handlers are your own functions that will be triggered in response to user interactions like clicking, hovering, focusing on form inputs, and so on.
内置组件如 <button> 只支持内置浏览器事件如 onClick。然而,你也可以创建自己的组件,并为它们的事件处理器属性命名任何你喜欢的应用特定名称。
🌐 Built-in components like <button> only support built-in browser events like onClick. However, you can also create your own components, and give their event handler props any application-specific names that you like.
export default function App() { return ( <Toolbar onPlayMovie={() => alert('Playing!')} onUploadImage={() => alert('Uploading!')} /> ); } function Toolbar({ onPlayMovie, onUploadImage }) { return ( <div> <Button onClick={onPlayMovie}> Play Movie </Button> <Button onClick={onUploadImage}> Upload Image </Button> </div> ); } function Button({ onClick, children }) { return ( <button onClick={onClick}> {children} </button> ); }
准备好学习这个主题了吗?
阅读 响应事件 以了解如何添加事件处理程序。
🌐 Read Responding to Events to learn how to add event handlers.
阅读更多状态:组件的内存
🌐 State: a component’s memory
组件经常需要根据用户的交互来改变屏幕上的内容。在表单中输入时应该更新输入字段,点击图片轮播中的“下一张”应更改显示的图片,点击“购买”会将产品放入购物车。组件需要“记住”一些东西:当前的输入值、当前的图片、购物车。在 React 中,这种组件特有的记忆被称为状态。
🌐 Components often need to change what’s on the screen as a result of an interaction. Typing into the form should update the input field, clicking “next” on an image carousel should change which image is displayed, clicking “buy” puts a product in the shopping cart. Components need to “remember” things: the current input value, the current image, the shopping cart. In React, this kind of component-specific memory is called state.
你可以使用 useState Hook 向组件添加状态。Hook 是特殊的函数,它让你的组件可以使用 React 的功能(状态就是其中之一)。useState Hook 允许你声明一个状态变量。它接收初始状态并返回一对值:当前状态和一个允许你更新状态的状态设置函数。
🌐 You can add state to a component with a useState Hook. Hooks are special functions that let your components use React features (state is one of those features). The useState Hook lets you declare a state variable. It takes the initial state and returns a pair of values: the current state, and a state setter function that lets you update it.
const [index, setIndex] = useState(0);
const [showMore, setShowMore] = useState(false);以下是图片库如何在点击时使用和更新状态:
🌐 Here is how an image gallery uses and updates state on click:
import { useState } from 'react'; import { sculptureList } from './data.js'; export default function Gallery() { const [index, setIndex] = useState(0); const [showMore, setShowMore] = useState(false); const hasNext = index < sculptureList.length - 1; function handleNextClick() { if (hasNext) { setIndex(index + 1); } else { setIndex(0); } } function handleMoreClick() { setShowMore(!showMore); } let sculpture = sculptureList[index]; return ( <> <button onClick={handleNextClick}> Next </button> <h2> <i>{sculpture.name} </i> by {sculpture.artist} </h2> <h3> ({index + 1} of {sculptureList.length}) </h3> <button onClick={handleMoreClick}> {showMore ? 'Hide' : 'Show'} details </button> {showMore && <p>{sculpture.description}</p>} <img src={sculpture.url} alt={sculpture.alt} /> </> ); }
准备好学习这个主题了吗?
阅读 State: 组件的内存 以了解如何记住一个值并在交互时更新它。
🌐 Read State: A Component’s Memory to learn how to remember a value and update it on interaction.
阅读更多渲染和提交
🌐 Render and commit
在你的组件显示在屏幕上之前,它们必须经过 React 的渲染。理解这一过程的步骤将帮助你思考代码是如何执行的,并解释其行为。
🌐 Before your components are displayed on the screen, they must be rendered by React. Understanding the steps in this process will help you think about how your code executes and explain its behavior.
想象你的组件就像厨房里的厨师,从各种食材中组装出美味的菜肴。在这种情况下,React 就是服务员,接收顾客的点单并将他们的餐点送达。这个请求和呈现用户界面的过程有三个步骤:
🌐 Imagine that your components are cooks in the kitchen, assembling tasty dishes from ingredients. In this scenario, React is the waiter who puts in requests from customers and brings them their orders. This process of requesting and serving UI has three steps:
- 触发 渲染(将食客的订单送到厨房)
- 渲染组件(在厨房准备订单)
- 提交到 DOM(将订单放在表格上)

Trigger 
Render 
Commit
Illustrated by Rachel Lee Nabors
准备好学习这个主题了吗?
阅读 渲染与提交 以了解 UI 更新的生命周期。
🌐 Read Render and Commit to learn the lifecycle of a UI update.
阅读更多状态快照
🌐 State as a snapshot
与普通的 JavaScript 变量不同,React 状态更像是一个快照。设置它并不会改变你已有的状态变量,而是触发重新渲染。起初这可能会让人感到惊讶!
🌐 Unlike regular JavaScript variables, React state behaves more like a snapshot. Setting it does not change the state variable you already have, but instead triggers a re-render. This can be surprising at first!
console.log(count); // 0
setCount(count + 1); // Request a re-render with 1
console.log(count); // Still 0!这种行为可以帮助你避免细微的错误。这里有一个小聊天应用。试着猜一下,如果你先按“发送”,然后再把收件人改成 Bob,会发生什么。五秒钟后,alert 中会出现谁的名字?
🌐 This behavior helps you avoid subtle bugs. Here is a little chat app. Try to guess what happens if you press “Send” first and then change the recipient to Bob. Whose name will appear in the alert five seconds later?
import { useState } from 'react'; export default function Form() { const [to, setTo] = useState('Alice'); const [message, setMessage] = useState('Hello'); function handleSubmit(e) { e.preventDefault(); setTimeout(() => { alert(`You said ${message} to ${to}`); }, 5000); } return ( <form onSubmit={handleSubmit}> <label> To:{' '} <select value={to} onChange={e => setTo(e.target.value)}> <option value="Alice">Alice</option> <option value="Bob">Bob</option> </select> </label> <textarea placeholder="Message" value={message} onChange={e => setMessage(e.target.value)} /> <button type="submit">Send</button> </form> ); }
准备好学习这个主题了吗?
阅读 State as a Snapshot 以了解为什么状态在事件处理程序内部看起来“固定”且不变。
🌐 Read State as a Snapshot to learn why state appears “fixed” and unchanging inside the event handlers.
阅读更多队列一系列状态更新
🌐 Queueing a series of state updates
这个组件有bug:点击“+3”只会将分数增加一次。
🌐 This component is buggy: clicking “+3” increments the score only once.
import { useState } from 'react'; export default function Counter() { const [score, setScore] = useState(0); function increment() { setScore(score + 1); } return ( <> <button onClick={() => increment()}>+1</button> <button onClick={() => { increment(); increment(); increment(); }}>+3</button> <h1>Score: {score}</h1> </> ) }
State as a Snapshot 解释了为什么会发生这种情况。设置状态会请求新的重新渲染,但不会改变已经正在运行的代码中的状态。因此,在你调用 setScore(score + 1) 之后,score 仍然是 0。
console.log(score); // 0
setScore(score + 1); // setScore(0 + 1);
console.log(score); // 0
setScore(score + 1); // setScore(0 + 1);
console.log(score); // 0
setScore(score + 1); // setScore(0 + 1);
console.log(score); // 0你可以通过在设置状态时传入一个更新函数来修复这个问题。注意将 setScore(score + 1) 替换为 setScore(s => s + 1) 如何修复了“+3”按钮。这让你能够排队多个状态更新。
🌐 You can fix this by passing an updater function when setting state. Notice how replacing setScore(score + 1) with setScore(s => s + 1) fixes the “+3” button. This lets you queue multiple state updates.
import { useState } from 'react'; export default function Counter() { const [score, setScore] = useState(0); function increment() { setScore(s => s + 1); } return ( <> <button onClick={() => increment()}>+1</button> <button onClick={() => { increment(); increment(); increment(); }}>+3</button> <h1>Score: {score}</h1> </> ) }
准备好学习这个主题了吗?
阅读 排队一系列状态更新 以了解如何排队一系列状态更新。
🌐 Read Queueing a Series of State Updates to learn how to queue a sequence of state updates.
阅读更多更新状态中的对象
🌐 Updating objects in state
状态可以保存任何类型的 JavaScript 值,包括对象。但你不应该直接更改你在 React 状态中持有的对象和数组。相反,当你想要更新对象和数组时,你需要创建一个新的(或复制一个现有的),然后更新状态以使用该副本。
🌐 State can hold any kind of JavaScript value, including objects. But you shouldn’t change objects and arrays that you hold in the React state directly. Instead, when you want to update an object and array, you need to create a new one (or make a copy of an existing one), and then update the state to use that copy.
通常,你会使用 ... 扩展语法来复制你想要修改的对象和数组。例如,更新一个嵌套对象可能看起来像这样:
🌐 Usually, you will use the ... spread syntax to copy objects and arrays that you want to change. For example, updating a nested object could look like this:
import { useState } from 'react'; export default function Form() { const [person, setPerson] = useState({ name: 'Niki de Saint Phalle', artwork: { title: 'Blue Nana', city: 'Hamburg', image: 'https://i.imgur.com/Sd1AgUOm.jpg', } }); function handleNameChange(e) { setPerson({ ...person, name: e.target.value }); } function handleTitleChange(e) { setPerson({ ...person, artwork: { ...person.artwork, title: e.target.value } }); } function handleCityChange(e) { setPerson({ ...person, artwork: { ...person.artwork, city: e.target.value } }); } function handleImageChange(e) { setPerson({ ...person, artwork: { ...person.artwork, image: e.target.value } }); } return ( <> <label> Name: <input value={person.name} onChange={handleNameChange} /> </label> <label> Title: <input value={person.artwork.title} onChange={handleTitleChange} /> </label> <label> City: <input value={person.artwork.city} onChange={handleCityChange} /> </label> <label> Image: <input value={person.artwork.image} onChange={handleImageChange} /> </label> <p> <i>{person.artwork.title}</i> {' by '} {person.name} <br /> (located in {person.artwork.city}) </p> <img src={person.artwork.image} alt={person.artwork.title} /> </> ); }
如果在代码中复制对象变得乏味,你可以使用像 Immer 这样的库来减少重复代码:
🌐 If copying objects in code gets tedious, you can use a library like Immer to reduce repetitive code:
{ "dependencies": { "immer": "1.7.3", "react": "latest", "react-dom": "latest", "react-scripts": "latest", "use-immer": "0.5.1" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test --env=jsdom", "eject": "react-scripts eject" }, "devDependencies": {} }
准备好学习这个主题了吗?
阅读 在状态中更新对象 以学习如何正确更新对象。
🌐 Read Updating Objects in State to learn how to update objects correctly.
阅读更多更新状态数组
🌐 Updating arrays in state
数组是另一种可以存储在状态中的可变 JavaScript 对象类型,并且应被视为只读。就像对象一样,当你想要更新存储在状态中的数组时,你需要创建一个新的数组(或复制一个现有的数组),然后将状态设置为使用新的数组:
🌐 Arrays are another type of mutable JavaScript objects you can store in state and should treat as read-only. Just like with objects, when you want to update an array stored in state, you need to create a new one (or make a copy of an existing one), and then set state to use the new array:
import { useState } from 'react'; const initialList = [ { id: 0, title: 'Big Bellies', seen: false }, { id: 1, title: 'Lunar Landscape', seen: false }, { id: 2, title: 'Terracotta Army', seen: true }, ]; export default function BucketList() { const [list, setList] = useState( initialList ); function handleToggle(artworkId, nextSeen) { setList(list.map(artwork => { if (artwork.id === artworkId) { return { ...artwork, seen: nextSeen }; } else { return artwork; } })); } return ( <> <h1>Art Bucket List</h1> <h2>My list of art to see:</h2> <ItemList artworks={list} onToggle={handleToggle} /> </> ); } function ItemList({ artworks, onToggle }) { return ( <ul> {artworks.map(artwork => ( <li key={artwork.id}> <label> <input type="checkbox" checked={artwork.seen} onChange={e => { onToggle( artwork.id, e.target.checked ); }} /> {artwork.title} </label> </li> ))} </ul> ); }
如果在代码中复制数组变得繁琐,你可以使用像 Immer 这样的库来减少重复代码:
🌐 If copying arrays in code gets tedious, you can use a library like Immer to reduce repetitive code:
{ "dependencies": { "immer": "1.7.3", "react": "latest", "react-dom": "latest", "react-scripts": "latest", "use-immer": "0.5.1" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test --env=jsdom", "eject": "react-scripts eject" }, "devDependencies": {} }
准备好学习这个主题了吗?
阅读 在状态中更新数组 以学习如何正确更新数组。
🌐 Read Updating Arrays in State to learn how to update arrays correctly.
阅读更多下一步是什么?
🌐 What’s next?
前往 回应事件 开始逐页阅读本章内容!
🌐 Head over to Responding to Events to start reading this chapter page by page!
或者,如果你已经熟悉这些主题,为什么不阅读一下状态管理呢?
🌐 Or, if you’re already familiar with these topics, why not read about Managing State?