Skip to content

Commit 89b870f

Browse files
authored
Merge pull request #37 from reactjs/uncontrolled-components
Translate Uncontrolled Components
2 parents ea20319 + 541b699 commit 89b870f

File tree

1 file changed

+19
-19
lines changed

1 file changed

+19
-19
lines changed

content/docs/uncontrolled-components.md

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
---
22
id: uncontrolled-components
3-
title: Uncontrolled Components
3+
title: Неконтролируемые компоненты
44
permalink: docs/uncontrolled-components.html
55
---
66

7-
In most cases, we recommend using [controlled components](/docs/forms.html) to implement forms. In a controlled component, form data is handled by a React component. The alternative is uncontrolled components, where form data is handled by the DOM itself.
7+
В большинстве случаев при работе с формами мы рекомендуем использовать [контролируемые компоненты](/docs/forms.html). В контролируемом компоненте, данные формы обрабатываются React-компонентом. В качестве альтернативы можно использовать неконтролируемые компоненты. Они хранят данные формы прямо в DOM.
88

9-
To write an uncontrolled component, instead of writing an event handler for every state update, you can [use a ref](/docs/refs-and-the-dom.html) to get form values from the DOM.
9+
Вместо того, чтобы писать обработчик события для каждого обновления состояния, вы можете использовать неконтролируемый компонент и читать значения из DOM через [реф](/docs/refs-and-the-dom.html).
1010

11-
For example, this code accepts a single name in an uncontrolled component:
11+
Вот так, к примеру, обработчик неконтролируемого компонента может получить имя от элемента `input`:
1212

1313
```javascript{5,9,18}
1414
class NameForm extends React.Component {
@@ -19,64 +19,64 @@ class NameForm extends React.Component {
1919
}
2020
2121
handleSubmit(event) {
22-
alert('A name was submitted: ' + this.input.current.value);
22+
alert('Отправленное имя: ' + this.input.current.value);
2323
event.preventDefault();
2424
}
2525
2626
render() {
2727
return (
2828
<form onSubmit={this.handleSubmit}>
2929
<label>
30-
Name:
30+
Имя:
3131
<input type="text" ref={this.input} />
3232
</label>
33-
<input type="submit" value="Submit" />
33+
<input type="submit" value="Отправить" />
3434
</form>
3535
);
3636
}
3737
}
3838
```
3939

40-
[**Try it on CodePen**](https://codepen.io/gaearon/pen/WooRWa?editors=0010)
40+
[**Посмотреть на CodePen**](https://codepen.io/gaearon/pen/WooRWa?editors=0010)
4141

42-
Since an uncontrolled component keeps the source of truth in the DOM, it is sometimes easier to integrate React and non-React code when using uncontrolled components. It can also be slightly less code if you want to be quick and dirty. Otherwise, you should usually use controlled components.
42+
Неконтролируемые компоненты опираются на DOM в качестве источника данных и могут быть удобны при интеграции React с кодом, не связанным с React. Количество кода может уменьшиться, правда, за счёт потери в его чистоте. Поэтому в обычных ситуациях мы рекомендуем использовать контролируемые компоненты.
4343

44-
If it's still not clear which type of component you should use for a particular situation, you might find [this article on controlled versus uncontrolled inputs](https://goshakkk.name/controlled-vs-uncontrolled-inputs-react/) to be helpful.
44+
Если всё ещё остаётся неясным, какой тип компонента лучше использовать в конкретной ситуации, то, возможно, [статья про сравнение контролируемых и некотролируемых полях ввода](https://goshakkk.name/controlled-vs-uncontrolled-inputs-react/) окажется полезной.
4545

46-
### Default Values {#default-values}
46+
### Значения по умолчанию {#default-values}
4747

48-
In the React rendering lifecycle, the `value` attribute on form elements will override the value in the DOM. With an uncontrolled component, you often want React to specify the initial value, but leave subsequent updates uncontrolled. To handle this case, you can specify a `defaultValue` attribute instead of `value`.
48+
На этапе рендеринга атрибут `value` полей ввода переопределяет значение в DOM. С неконтролируемым компонентом зачастую нужно, чтобы React опредил первоначальное значение, но впоследствии ничего не делал с ним. В этом случае необходимо определить атрибут `defaultValue` вместо `value`.
4949

5050
```javascript{7}
5151
render() {
5252
return (
5353
<form onSubmit={this.handleSubmit}>
5454
<label>
55-
Name:
55+
Имя:
5656
<input
5757
defaultValue="Bob"
5858
type="text"
5959
ref={this.input} />
6060
</label>
61-
<input type="submit" value="Submit" />
61+
<input type="submit" value="Отправить" />
6262
</form>
6363
);
6464
}
6565
```
6666

67-
Likewise, `<input type="checkbox">` and `<input type="radio">` support `defaultChecked`, and `<select>` and `<textarea>` supports `defaultValue`.
67+
Аналогично, `<input type="checkbox">` и `<input type="radio">` используют `defaultChecked`, а `<select>` и `<textarea>` `defaultValue`.
6868

69-
## The file input Tag {#the-file-input-tag}
69+
## Тег поля загрузки файла {#the-file-input-tag}
7070

71-
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).
71+
HTML-тег `<input type="file">` позволяет пользователю выбрать один или несколько файлов из дискового устройства, чтобы загрузить их на сервер, либо управлять ими с помощью JavaScript через [File API](https://developer.mozilla.org/ru/docs/Web/API/File/Using_files_from_web_applications).
7272

7373
```html
7474
<input type="file" />
7575
```
7676

77-
In React, an `<input type="file" />` is always an uncontrolled component because its value can only be set by a user, and not programmatically.
77+
В React `<input type="file">` всегда является неконтролируемым компонентом, потому что его значение может быть установлено только пользователем, а не программным путём.
7878

79-
You should use the File API to interact with the files. The following example shows how to create a [ref to the DOM node](/docs/refs-and-the-dom.html) to access file(s) in a submit handler:
79+
Для взаимодействия с файлами следует использовать File API. В следующем примере показано, как создать [реф на DOM-узел](/docs/refs-and-the-dom.html), чтобы затем получить доступ к файлам в обработчике отправки формы:
8080

8181
`embed:uncontrolled-components/input-type-file.js`
8282

0 commit comments

Comments
 (0)