Skip to content

Commit ed8d500

Browse files
docs: translate form.md to Русский
1 parent 2958f53 commit ed8d500

1 file changed

Lines changed: 38 additions & 38 deletions

File tree

  • src/content/reference/react-dom/components

src/content/reference/react-dom/components/form.md

Lines changed: 38 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ title: "<form>"
44

55
<Intro>
66

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>` позволяет создавать интерактивные элементы для отправки информации.
88

99
```js
1010
<form action={search}>
@@ -19,11 +19,11 @@ The [built-in browser `<form>` component](https://developer.mozilla.org/en-US/do
1919

2020
---
2121

22-
## Reference {/*reference*/}
22+
## Справочник {/*reference*/}
2323

2424
### `<form>` {/*form*/}
2525

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>`.
2727

2828
```js
2929
<form action={search}>
@@ -32,25 +32,25 @@ To create interactive controls for submitting information, render the [built-in
3232
</form>
3333
```
3434

35-
[See more examples below.](#usage)
35+
[См. примеры ниже.](#usage)
3636

37-
#### Props {/*props*/}
37+
#### Пропсы {/*props*/}
3838

39-
`<form>` supports all [common element props.](/reference/react-dom/components/common#props)
39+
`<form>` поддерживает все [общие пропсы элементов](/reference/react-dom/components/common#props).
4040

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">`.
4242

43-
#### Caveats {/*caveats*/}
43+
#### Ограничения {/*caveats*/}
4444

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`.
4646

4747
---
4848

49-
## Usage {/*usage*/}
49+
## Использование {/*usage*/}
5050

51-
### Handle form submission on the client {/*handle-form-submission-on-the-client*/}
51+
### Обработка отправки формы на клиенте {/*handle-form-submission-on-the-client*/}
5252

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` все неуправляемые элементы полей в форме сбрасываются.
5454

5555
<Sandpack>
5656

@@ -71,13 +71,13 @@ export default function Search() {
7171

7272
</Sandpack>
7373

74-
### Handle form submission with a Server Function {/*handle-form-submission-with-a-server-function*/}
74+
### Обработка отправки формы с помощью серверной функции {/*handle-form-submission-with-a-server-function*/}
7575

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` формы, чтобы выполнить эту функцию при отправке формы.
7777

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`.
7979

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).
8181

8282
```jsx
8383
import { updateCart } from './lib.js';
@@ -98,7 +98,7 @@ function AddToCart({productId}) {
9898
}
9999
```
100100

101-
In lieu of using hidden form fields to provide data to the `<form>`'s action, you can call the <CodeStep step={1}>`bind`</CodeStep> method to supply it with extra arguments. This will bind a new argument (<CodeStep step={2}>`productId`</CodeStep>) to the function in addition to the <CodeStep step={3}>`formData`</CodeStep> that is passed as an argument to the function.
101+
Вместо использования скрытых полей формы для предоставления данных действию `<form>`, вы можете вызвать метод <CodeStep step={1}>`bind`</CodeStep>, чтобы передать ему дополнительные аргументы. Это привяжет новый аргумент (<CodeStep step={2}>`productId`</CodeStep>) к функции в дополнение к <CodeStep step={3}>`formData`</CodeStep>, который передается в качестве аргумента функции.
102102

103103
```jsx [[1, 8, "bind"], [2,8, "productId"], [2,4, "productId"], [3,4, "formData"]]
104104
import { updateCart } from './lib.js';
@@ -117,12 +117,12 @@ function AddToCart({productId}) {
117117
}
118118
```
119119

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).
121121

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`.
124124

125-
Here, we use the `pending` property to indicate the form is submitting.
125+
Здесь мы используем свойство `pending`, чтобы указать, что форма отправляется.
126126

127127
<Sandpack>
128128

@@ -160,12 +160,12 @@ export async function submitForm(query) {
160160

161161
</Sandpack>
162162

163-
To learn more about the `useFormStatus` Hook see the [reference documentation](/reference/react-dom/hooks/useFormStatus).
163+
Чтобы узнать больше о хуке `useFormStatus`, см. [справочную документацию](/reference/react-dom/hooks/useFormStatus).
164164

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` предоставляет способ оптимистичного обновления пользовательского интерфейса до завершения фоновой операции, такой как сетевой запрос. В контексте форм этот метод помогает сделать приложения более отзывчивыми. Когда пользователь отправляет форму, вместо ожидания ответа сервера для отражения изменений, интерфейс немедленно обновляется с ожидаемым результатом.
167167

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` позволяет сообщению немедленно появиться в списке с меткой "Отправка...", еще до того, как сообщение будет фактически отправлено на сервер. Этот "оптимистичный" подход создает впечатление скорости и отзывчивости. Затем форма пытается действительно отправить сообщение в фоновом режиме. Как только сервер подтвердит получение сообщения, метка "Отправка..." будет удалена.
169169

170170
<Sandpack>
171171

@@ -232,9 +232,9 @@ export async function deliverMessage(message) {
232232
[//]: # 'Uncomment the next line, and delete this line after the `useOptimistic` reference documentatino page is published'
233233
[//]: # 'To learn more about the `useOptimistic` Hook see the [reference documentation](/reference/react/hooks/useOptimistic).'
234234

235-
### Handling form submission errors {/*handling-form-submission-errors*/}
235+
### Обработка ошибок отправки формы {/*handling-form-submission-errors*/}
236236

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.
238238

239239
<Sandpack>
240240

@@ -274,15 +274,15 @@ export default function Search() {
274274

275275
</Sandpack>
276276

277-
### Display a form submission error without JavaScript {/*display-a-form-submission-error-without-javascript*/}
277+
### Отображение сообщения об ошибке отправки формы без JavaScript {/*display-a-form-submission-error-without-javascript*/}
278278

279-
Displaying a form submission error message before the JavaScript bundle loads for progressive enhancement requires that:
279+
Отображение сообщения об ошибке отправки формы до загрузки JavaScript-пакета для прогрессивного улучшения требует:
280280

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` должен использоваться для отображения сообщения об ошибке.
284284

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`, будет использоваться для обновления переменной состояния.
286286

287287
<Sandpack>
288288

@@ -330,13 +330,13 @@ export async function signUpNewUser(newEmail) {
330330

331331
</Sandpack>
332332

333-
Learn more about updating state from a form action with the [`useActionState`](/reference/react/useActionState) docs
333+
Узнайте больше об обновлении состояния из действия формы в документации [`useActionState`](/reference/react/useActionState).
334334

335-
### Handling multiple submission types {/*handling-multiple-submission-types*/}
335+
### Обработка нескольких типов отправки {/*handling-multiple-submission-types*/}
336336

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`.
338338

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`, установленным на сохранение статьи в черновик.
340340

341341
<Sandpack>
342342

@@ -364,4 +364,4 @@ export default function Search() {
364364
}
365365
```
366366

367-
</Sandpack>
367+
</Sandpack>

0 commit comments

Comments
 (0)