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
Copy file name to clipboardExpand all lines: src/content/reference/react-dom/components/form.md
+38-38Lines changed: 38 additions & 38 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -4,7 +4,7 @@ title: "<form>"
4
4
5
5
<Intro>
6
6
7
-
The [built-in browser`<form>`component](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) lets you create interactive controls for submitting information.
7
+
Встроенный компонент браузера`<form>`позволяет создавать интерактивные элементы для отправки информации.
8
8
9
9
```js
10
10
<form action={search}>
@@ -19,11 +19,11 @@ The [built-in browser `<form>` component](https://developer.mozilla.org/en-US/do
19
19
20
20
---
21
21
22
-
## Reference {/*reference*/}
22
+
## Справочник {/*reference*/}
23
23
24
24
### `<form>` {/*form*/}
25
25
26
-
To create interactive controls for submitting information, render the [built-in browser`<form>` component](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form).
26
+
Для создания интерактивных элементов для отправки информации используйте встроенный компонент браузера`<form>`.
27
27
28
28
```js
29
29
<form action={search}>
@@ -32,25 +32,25 @@ To create interactive controls for submitting information, render the [built-in
32
32
</form>
33
33
```
34
34
35
-
[See more examples below.](#usage)
35
+
[См. примеры ниже.](#usage)
36
36
37
-
#### Props {/*props*/}
37
+
#### Пропсы {/*props*/}
38
38
39
-
`<form>`supports all [common element props.](/reference/react-dom/components/common#props)
39
+
`<form>`поддерживает все [общие пропсы элементов](/reference/react-dom/components/common#props).
40
40
41
-
[`action`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#action): a URL or function. When a URL is passed to `action`the form will behave like the HTML form component. When a function is passed to `action`the function will handle the form submission. The function passed to `action` may be async and will be called with a single argument containing the [form data](https://developer.mozilla.org/en-US/docs/Web/API/FormData)of the submitted form. The`action`prop can be overridden by a `formAction`attribute on a `<button>`, `<input type="submit">`, or`<input type="image">` component.
41
+
[`action`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#action): URL или функция. При передаче URL в `action`форма будет вести себя как HTML-компонент формы. При передаче функции в `action`функция будет обрабатывать отправку формы. Функция, переданная в `action`, может быть асинхронной и будет вызвана с одним аргументом, содержащим [данные формы](https://developer.mozilla.org/en-US/docs/Web/API/FormData)отправленной формы. Пропс`action`может быть переопределен атрибутом `formAction`на компоненте `<button>`, `<input type="submit">` или`<input type="image">`.
42
42
43
-
#### Caveats {/*caveats*/}
43
+
#### Ограничения {/*caveats*/}
44
44
45
-
*When a function is passed to `action`or`formAction`the HTTP method will be POST regardless of value of the `method` prop.
45
+
*При передаче функции в `action`или`formAction` HTTP-метод будет POST, независимо от значения пропа `method`.
46
46
47
47
---
48
48
49
-
## Usage {/*usage*/}
49
+
## Использование {/*usage*/}
50
50
51
-
### Handle form submission on the client {/*handle-form-submission-on-the-client*/}
51
+
### Обработка отправки формы на клиенте {/*handle-form-submission-on-the-client*/}
52
52
53
-
Pass a function to the `action`prop of form to run the function when the form is submitted. [`formData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData)will be passed to the function as an argument so you can access the data submitted by the form. This differs from the conventional [HTML action](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#action), which only accepts URLs. After the `action`function succeeds, all uncontrolled field elements in the form are reset.
53
+
Передайте функцию в пропс `action`формы, чтобы выполнить эту функцию при отправке формы. [`formData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData)будет передана в функцию в качестве аргумента, чтобы вы могли получить доступ к данным, отправленным формой. Это отличается от стандартного [HTML `action`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#action), который принимает только URL. После успешного выполнения функции `action`все неуправляемые элементы полей в форме сбрасываются.
54
54
55
55
<Sandpack>
56
56
@@ -71,13 +71,13 @@ export default function Search() {
71
71
72
72
</Sandpack>
73
73
74
-
### Handle form submission with a Server Function {/*handle-form-submission-with-a-server-function*/}
74
+
### Обработка отправки формы с помощью серверной функции {/*handle-form-submission-with-a-server-function*/}
75
75
76
-
Render a `<form>`with an input and submit button. Pass a Server Function (a function marked with [`'use server'`](/reference/rsc/use-server)) to the`action`prop of form to run the function when the form is submitted.
76
+
Отобразите `<form>`с полем ввода и кнопкой отправки. Передайте серверную функцию (функцию, помеченную [`'use server'`](/reference/rsc/use-server)) в пропс`action`формы, чтобы выполнить эту функцию при отправке формы.
77
77
78
-
Passing a Server Function to `<form action>`allow users to submit forms without JavaScript enabled or before the code has loaded. This is beneficial to users who have a slow connection, device, or have JavaScript disabled and is similar to the way forms work when a URL is passed to the `action` prop.
78
+
Передача серверной функции в `<form action>`позволяет пользователям отправлять формы без включенного JavaScript или до загрузки кода. Это полезно для пользователей с медленным соединением, устройством или отключенным JavaScript, и похоже на то, как работают формы при передаче URL в пропс `action`.
79
79
80
-
You can use hidden form fields to provide data to the `<form>`'s action. The Server Function will be called with the hidden form field data as an instance of[`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData).
80
+
Вы можете использовать скрытые поля формы для предоставления данных действию `<form>`. Серверная функция будет вызвана с данными скрытого поля формы в виде экземпляра[`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData).
81
81
82
82
```jsx
83
83
import { updateCart } from'./lib.js';
@@ -98,7 +98,7 @@ function AddToCart({productId}) {
98
98
}
99
99
```
100
100
101
-
In lieu of using hidden form fields to provide data to the `<form>`'s action, you can call the <CodeStepstep={1}>`bind`</CodeStep> method to supply it with extra arguments. This will bind a new argument (<CodeStepstep={2}>`productId`</CodeStep>) to the function in addition to the <CodeStepstep={3}>`formData`</CodeStep> that is passed as an argument to the function.
101
+
Вместо использования скрытых полей формы для предоставления данных действию `<form>`, вы можете вызвать метод <CodeStepstep={1}>`bind`</CodeStep>, чтобы передать ему дополнительные аргументы. Это привяжет новый аргумент (<CodeStepstep={2}>`productId`</CodeStep>) к функции в дополнение к <CodeStepstep={3}>`formData`</CodeStep>, который передается в качестве аргумента функции.
@@ -117,12 +117,12 @@ function AddToCart({productId}) {
117
117
}
118
118
```
119
119
120
-
When`<form>`is rendered by a [Server Component](/reference/rsc/use-client), and a [Server Function](/reference/rsc/server-functions)is passed to the`<form>`'s `action` prop, the form is [progressively enhanced](https://developer.mozilla.org/en-US/docs/Glossary/Progressive_Enhancement).
120
+
Когда`<form>`отображается [серверным компонентом](/reference/rsc/use-client), а [серверная функция](/reference/rsc/server-functions)передается в пропс `action``<form>`, форма [прогрессивно улучшается](https://developer.mozilla.org/en-US/docs/Glossary/Progressive_Enhancement).
121
121
122
-
### Display a pending state during form submission {/*display-a-pending-state-during-form-submission*/}
123
-
To display a pending state when a form is being submitted, you can call the`useFormStatus`Hook in a component rendered in a `<form>` and read the `pending` property returned.
122
+
### Отображение состояния ожидания во время отправки формы {/*display-a-pending-state-during-form-submission*/}
123
+
Чтобы отобразить состояние ожидания во время отправки формы, вы можете вызвать хук`useFormStatus`в компоненте, отображаемом в `<form>`, и прочитать возвращаемое свойство `pending`.
124
124
125
-
Here, we use the`pending` property to indicate the form is submitting.
125
+
Здесь мы используем свойство`pending`, чтобы указать, что форма отправляется.
126
126
127
127
<Sandpack>
128
128
@@ -160,12 +160,12 @@ export async function submitForm(query) {
160
160
161
161
</Sandpack>
162
162
163
-
To learn more about the`useFormStatus` Hook see the [reference documentation](/reference/react-dom/hooks/useFormStatus).
163
+
Чтобы узнать больше о хуке`useFormStatus`, см. [справочную документацию](/reference/react-dom/hooks/useFormStatus).
164
164
165
-
### Optimistically updating form data {/*optimistically-updating-form-data*/}
166
-
The`useOptimistic`Hook provides a way to optimistically update the user interface before a background operation, like a network request, completes. In the context of forms, this technique helps to make apps feel more responsive. When a user submits a form, instead of waiting for the server's response to reflect the changes, the interface is immediately updated with the expected outcome.
165
+
### Оптимистичное обновление данных формы {/*optimistically-updating-form-data*/}
166
+
Хук`useOptimistic`предоставляет способ оптимистичного обновления пользовательского интерфейса до завершения фоновой операции, такой как сетевой запрос. В контексте форм этот метод помогает сделать приложения более отзывчивыми. Когда пользователь отправляет форму, вместо ожидания ответа сервера для отражения изменений, интерфейс немедленно обновляется с ожидаемым результатом.
167
167
168
-
For example, when a user types a message into the form and hits the "Send" button, the`useOptimistic`Hook allows the message to immediately appear in the list with a "Sending..." label, even before the message is actually sent to a server. This "optimistic" approach gives the impression of speed and responsiveness. The form then attempts to truly send the message in the background. Once the server confirms the message has been received, the "Sending..." label is removed.
168
+
Например, когда пользователь вводит сообщение в форму и нажимает кнопку "Отправить", хук`useOptimistic`позволяет сообщению немедленно появиться в списке с меткой "Отправка...", еще до того, как сообщение будет фактически отправлено на сервер. Этот "оптимистичный" подход создает впечатление скорости и отзывчивости. Затем форма пытается действительно отправить сообщение в фоновом режиме. Как только сервер подтвердит получение сообщения, метка "Отправка..." будет удалена.
169
169
170
170
<Sandpack>
171
171
@@ -232,9 +232,9 @@ export async function deliverMessage(message) {
232
232
[//]: #'Uncomment the next line, and delete this line after the `useOptimistic` reference documentatino page is published'
233
233
[//]: #'To learn more about the `useOptimistic` Hook see the [reference documentation](/reference/react/hooks/useOptimistic).'
234
234
235
-
### Handling form submission errors {/*handling-form-submission-errors*/}
235
+
### Обработка ошибок отправки формы {/*handling-form-submission-errors*/}
236
236
237
-
In some cases the function called by a `<form>`'s `action`prop throws an error. You can handle these errors by wrapping `<form>`in an Error Boundary. If the function called by a `<form>`'s `action`prop throws an error, the fallback for the error boundary will be displayed.
237
+
В некоторых случаях функция, вызываемая пропсом `action`формы, генерирует ошибку. Вы можете обрабатывать эти ошибки, оборачивая `<form>`в Error Boundary. Если функция, вызываемая пропсом `action`формы, генерирует ошибку, будет отображаться резервный вариант для error boundary.
238
238
239
239
<Sandpack>
240
240
@@ -274,15 +274,15 @@ export default function Search() {
274
274
275
275
</Sandpack>
276
276
277
-
### Display a form submission error without JavaScript {/*display-a-form-submission-error-without-javascript*/}
277
+
### Отображение сообщения об ошибке отправки формы без JavaScript {/*display-a-form-submission-error-without-javascript*/}
278
278
279
-
Displaying a form submission error message before the JavaScript bundle loads for progressive enhancement requires that:
279
+
Отображение сообщения об ошибке отправки формы до загрузки JavaScript-пакета для прогрессивного улучшения требует:
280
280
281
-
1.`<form>`be rendered by a [Server Component](/reference/rsc/use-client)
282
-
1.the function passed to the`<form>`'s `action` prop be a [Server Function](/reference/rsc/server-functions)
283
-
1.the`useActionState`Hook be used to display the error message
281
+
1.`<form>`должен быть отрисован [серверным компонентом](/reference/rsc/use-client).
282
+
1.Функция, переданная в пропс `action``<form>`, должна быть [серверной функцией](/reference/rsc/server-functions).
283
+
1.Хук`useActionState`должен использоваться для отображения сообщения об ошибке.
284
284
285
-
`useActionState`takes two parameters: a [Server Function](/reference/rsc/server-functions)and an initial state. `useActionState`returns two values, a state variable and an action. The action returned by `useActionState` should be passed to the`action`prop of the form. The state variable returned by `useActionState` can be used to display an error message. The value returned by the Server Function passed to `useActionState` will be used to update the state variable.
285
+
`useActionState`принимает два параметра: [серверную функцию](/reference/rsc/server-functions)и начальное состояние. `useActionState`возвращает два значения: переменную состояния и действие. Действие, возвращаемое `useActionState`, должно быть передано в пропс`action`формы. Переменная состояния, возвращаемая `useActionState`, может использоваться для отображения сообщения об ошибке. Значение, возвращаемое серверной функцией, переданной в `useActionState`, будет использоваться для обновления переменной состояния.
286
286
287
287
<Sandpack>
288
288
@@ -330,13 +330,13 @@ export async function signUpNewUser(newEmail) {
330
330
331
331
</Sandpack>
332
332
333
-
Learn more about updating state from a form action with the [`useActionState`](/reference/react/useActionState) docs
333
+
Узнайте больше об обновлении состояния из действия формы в документации [`useActionState`](/reference/react/useActionState).
### Обработка нескольких типов отправки {/*handling-multiple-submission-types*/}
336
336
337
-
Forms can be designed to handle multiple submission actions based on the button pressed by the user. Each button inside a form can be associated with a distinct action or behavior by setting the `formAction` prop.
337
+
Формы могут быть разработаны для обработки нескольких действий отправки в зависимости от нажатой пользователем кнопки. Каждая кнопка внутри формы может быть связана с отдельным действием или поведением путем установки пропса `formAction`.
338
338
339
-
When a user taps a specific button, the form is submitted, and a corresponding action, defined by that button's attributes and action, is executed. For instance, a form might submit an article for review by default but have a separate button with `formAction` set to save the article as a draft.
339
+
Когда пользователь нажимает определенную кнопку, форма отправляется, и выполняется соответствующее действие, определяемое атрибутами и действием этой кнопки. Например, форма может отправлять статью на рассмотрение по умолчанию, но иметь отдельную кнопку с `formAction`, установленным на сохранение статьи в черновик.
340
340
341
341
<Sandpack>
342
342
@@ -364,4 +364,4 @@ export default function Search() {
0 commit comments