You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
HTML form elements work a little bit differently from other DOM elements in React, because form elements naturally keep some internal state. For example, this form in plain HTML accepts a single name:
12
+
在 React 里,HTML 表单元素的工作方式和其他的 DOM 元素有些不同,这是因为表单元素通常会保持一些内部的 state。例如这个纯 HTML 表单只接受一个名称:
13
13
14
14
```html
15
15
<form>
16
16
<label>
17
-
Name:
17
+
名字:
18
18
<inputtype="text"name="name" />
19
19
</label>
20
-
<inputtype="submit"value="Submit" />
20
+
<inputtype="submit"value="提交" />
21
21
</form>
22
22
```
23
23
24
-
This form has the default HTML form behavior of browsing to a new page when the user submits the form. If you want this behavior in React, it just works. But in most cases, it's convenient to have a JavaScript function that handles the submission of the form and has access to the data that the user entered into the form. The standard way to achieve this is with a technique called "controlled components".
24
+
此表单具有默认的 HTML 表单行为,即在用户提交表单后浏览到新页面。如果你在 React 中执行相同的代码,它依然有效。但大多数情况下,使用 JavaScript 函数可以很方便的处理表单的提交, 同时还可以访问用户填写的表单数据。实现这种效果的标准方式是使用“受控组件”。
25
25
26
-
## Controlled Components {#controlled-components}
26
+
## 受控组件 {#controlled-components}
27
27
28
-
In HTML, form elements such as `<input>`,`<textarea>`, and`<select>` typically maintain their own state and update it based on user input. In React, mutable state is typically kept in the state property of components, and only updated with [`setState()`](/docs/react-component.html#setstate).
28
+
在 HTML 中,表单元素(如`<input>`、`<textarea>` 和`<select>`)之类的表单元素通常自己维护 state,并根据用户输入进行更新。而在 React 中,可变状态(mutable state)通常保存在组件的 state 属性中,并且只能通过使用 [`setState()`](/docs/react-component.html#setstate)来更新。
29
29
30
-
We can combine the two by making the React state be the "single source of truth". Then the React component that renders a form also controls what happens in that form on subsequent user input. An input form element whose value is controlled by React in this way is called a "controlled component".
30
+
我们可以把两者结合起来,使 React 的 state 成为“唯一数据源”。渲染表单的 React 组件还控制着用户输入过程中表单发生的操作。被 React 以这种方式控制取值的表单输入元素就叫做“受控组件”。
31
31
32
-
For example, if we want to make the previous example log the name when it is submitted, we can write the form as a controlled component:
32
+
例如,如果我们想让前一个示例在提交时打印出名称,我们可以将表单写为受控组件:
33
33
34
34
```javascript{4,10-12,24}
35
35
class NameForm extends React.Component {
@@ -46,54 +46,54 @@ class NameForm extends React.Component {
46
46
}
47
47
48
48
handleSubmit(event) {
49
-
alert('A name was submitted: ' + this.state.value);
Since the `value`attribute is set on our form element, the displayed value will always be `this.state.value`, making the React state the source of truth. Since `handleChange` runs on every keystroke to update the React state, the displayed value will update as the user types.
With a controlled component, every state mutation will have an associated handler function. This makes it straightforward to modify or validate user input. For example, if we wanted to enforce that names are written with all uppercase letters, we could write `handleChange` as:
71
+
对于受控组件来说,每个 state 突变都有一个相关的处理函数。这使得修改或验证用户输入变得简单。例如,如果我们要强制要求所有名称都用大写字母书写,我们可以将 `handlechange` 改写为:
In HTML, a `<textarea>`element defines its text by its children:
81
+
在 HTML 中, `<textarea>`元素通过其子元素定义其文本:
82
82
83
83
```html
84
84
<textarea>
85
-
Hello there, this is some text in a text area
85
+
你好, 这是在 text area 里的文本
86
86
</textarea>
87
87
```
88
88
89
-
In React, a `<textarea>`uses a `value`attribute instead. This way, a form using a `<textarea>`can be written very similarly to a form that uses a single-line input:
Notice that `this.state.value`is initialized in the constructor, so that the text area starts off with some text in it.
126
+
请注意,`this.state.value`初始化于构造函数中,因此文本区域默认有初值。
127
127
128
-
## The select Tag {#the-select-tag}
128
+
## select 标签 {#the-select-tag}
129
129
130
-
In HTML, `<select>`creates a drop-down list. For example, this HTML creates a drop-down list of flavors:
130
+
在 HTML 中,`<select>`创建下拉列表标签。例如,如下 HTML 创建了水果相关的下拉列表:
131
131
132
132
```html
133
133
<select>
134
-
<optionvalue="grapefruit">Grapefruit</option>
135
-
<optionvalue="lime">Lime</option>
136
-
<optionselectedvalue="coconut">Coconut</option>
137
-
<optionvalue="mango">Mango</option>
134
+
<optionvalue="grapefruit">葡萄柚</option>
135
+
<optionvalue="lime">柠檬</option>
136
+
<optionselectedvalue="coconut">椰子</option>
137
+
<optionvalue="mango">芒果</option>
138
138
</select>
139
139
```
140
140
141
-
Note that the Coconut option is initially selected, because of the `selected`attribute. React, instead of using this `selected`attribute, uses a `value` attribute on the root `select` tag. This is more convenient in a controlled component because you only need to update it in one place. For example:
Overall, this makes it so that `<input type="text">`, `<textarea>`, and`<select>`all work very similarly - they all accept a `value`attribute that you can use to implement a controlled component.
> You can pass an array into the `value`attribute, allowing you to select multiple options in a `select`tag:
187
+
> 你可以将数组传递到 `value`属性中,以支持在 `select`标签中选择多个选项:
188
188
>
189
189
>```js
190
190
><select multiple={true} value={['B', 'C']}>
191
191
>```
192
192
193
-
## The file input Tag {#the-file-input-tag}
193
+
## 文件 input 标签 {#the-file-input-tag}
194
194
195
-
In HTML, an `<input type="file">`lets the user choose one or more files from their device storage to be uploaded to a server or manipulated by JavaScript via the [File API](https://developer.mozilla.org/en-US/docs/Web/API/File/Using_files_from_web_applications).
195
+
在 HTML 中,`<input type=“file”>`允许用户从存储设备中选择一个或多个文件,将其上传到服务器,或通过使用 JavaScript 的 [File API](https://developer.mozilla.org/en-US/docs/Web/API/File/Using_files_from_web_applications) 进行控制。
196
196
197
197
```html
198
198
<input type="file"/>
199
199
```
200
200
201
-
Because its value is read-only, it is an **uncontrolled** component in React. It is discussed together with other uncontrolled components [later in the documentation](/docs/uncontrolled-components.html#the-file-input-tag).
201
+
因为它的 value 只读,所以它是 React 中的一个**非受控**组件。将与其他非受控组件[在后续文档中](/docs/uncontrolled-components.html#the-file-input-tag)一起讨论。
When you need to handle multiple controlled `input`elements, you can add a `name`attribute to each element and let the handler function choose what to do based on the value of `event.target.name`.
Note how we used the ES6 [computed property name](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names) syntax to update the state key corresponding to the given input name:
259
+
这里使用了 ES6 [计算属性名称](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names)的语法更新给定输入名称对应的 state 值:
260
+
261
+
例如:
260
262
261
263
```js{2}
262
264
this.setState({
263
265
[name]: value
264
266
});
265
267
```
266
268
267
-
It is equivalent to this ES5 code:
269
+
等同 ES5:
268
270
269
271
```js{2}
270
272
var partialState = {};
271
273
partialState[name] = value;
272
274
this.setState(partialState);
273
275
```
274
276
275
-
Also, since `setState()`automatically [merges a partial state into the current state](/docs/state-and-lifecycle.html#state-updates-are-merged), we only needed to call it with the changed parts.
277
+
另外,由于 `setState()`自动[将部分 state 合并到当前 state](/docs/state-and-lifecycle.html#state-updates-are-merged), 只需调用它更改部分 state 即可。
276
278
277
-
## Controlled Input Null Value {#controlled-input-null-value}
279
+
## 受控输入空值 {#controlled-input-null-value}
278
280
279
-
Specifying the value prop on a [controlled component](/docs/forms.html#controlled-components) prevents the user from changing the input unless you desire so. If you've specified a `value` but the input is still editable, you may have accidentally set `value`to `undefined`or`null`.
281
+
在[受控组件](/docs/forms.html#controlled-components)上指定 value 的 prop 可以防止用户更改输入。如果指定了 `value`,但输入仍可编辑,则可能是意外地将`value`设置为 `undefined`或`null`。
280
282
281
-
The following code demonstrates this. (The input is locked at first but becomes editable after a short delay.)
283
+
下面的代码演示了这一点。(输入最初被锁定,但在短时间延迟后变为可编辑。)
282
284
283
285
```javascript
284
286
ReactDOM.render(<input value="hi"/>, mountNode);
@@ -289,10 +291,10 @@ setTimeout(function() {
289
291
290
292
```
291
293
292
-
## Alternatives to Controlled Components {#alternatives-to-controlled-components}
It can sometimes be tedious to use controlled components, because you need to write an event handler for every way your data can change and pipe all of the input state through a React component. This can become particularly annoying when you are converting a preexisting codebase to React, or integrating a React application with a non-React library. In these situations, you might want to check out [uncontrolled components](/docs/uncontrolled-components.html), an alternative technique for implementing input forms.
If you're looking for a complete solution including validation, keeping track of the visited fields, and handling form submission, [Formik](https://jaredpalmer.com/formik)is one of the popular choices. However, it is built on the same principles of controlled components and managing state — so don't neglect to learn them.
300
+
如果你想寻找包含验证、追踪访问字段以及处理表单提交的完整解决方案,使用 [Formik](https://jaredpalmer.com/formik)是不错的选择。然而,它也是建立在受控组件和管理 state 的基础之上——所以不要忽视学习它们。
0 commit comments