Skip to content

Commit c882747

Browse files
authored
Merge pull request #856 from mekarthedev/translate-useId
Translate useId
2 parents 8772caf + 266db72 commit c882747

File tree

1 file changed

+47
-47
lines changed

1 file changed

+47
-47
lines changed

src/content/reference/react/useId.md

+47-47
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ title: useId
44

55
<Intro>
66

7-
`useId` is a React Hook for generating unique IDs that can be passed to accessibility attributes.
7+
Хук `useId` позволяет создавать уникальные идентификаторы, которые затем можно использовать, например, в атрибутах доступности.
88

99
```js
1010
const id = useId()
@@ -16,11 +16,11 @@ const id = useId()
1616

1717
---
1818

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

2121
### `useId()` {/*useid*/}
2222

23-
Call `useId` at the top level of your component to generate a unique ID:
23+
Чтобы создать уникальный идентификатор, вызовите `useId` на верхнем уровне своего компонента:
2424

2525
```js
2626
import { useId } from 'react';
@@ -30,35 +30,35 @@ function PasswordField() {
3030
// ...
3131
```
3232
33-
[See more examples below.](#usage)
33+
[См. другие примеры ниже.](#usage)
3434
35-
#### Parameters {/*parameters*/}
35+
#### Параметры {/*parameters*/}
3636
37-
`useId` does not take any parameters.
37+
`useId` не принимает параметров.
3838
39-
#### Returns {/*returns*/}
39+
#### Возвращаемое значение {/*returns*/}
4040
41-
`useId` returns a unique ID string associated with this particular `useId` call in this particular component.
41+
`useId` возвращает уникальный идентификатор, привязанный к данному конкретному вызову `useId` в данном конкретном компоненте.
4242
43-
#### Caveats {/*caveats*/}
43+
#### Замечания {/*caveats*/}
4444
45-
* `useId` is a Hook, so you can only call it **at the top level of your component** or your own Hooks. You can't call it inside loops or conditions. If you need that, extract a new component and move the state into it.
45+
* `useId` -- это хук, поэтому его нужно вызывать только **на верхнем уровне вашего компонента** или хука. Его нельзя вызывать внутри циклов и условий. Если это всё же для чего-то нужно, выделите этот вызов в отдельный компонент, который затем можно рендерить по условию или в цикле.
4646
47-
* `useId` **should not be used to generate keys** in a list. [Keys should be generated from your data.](/learn/rendering-lists#where-to-get-your-key)
47+
* `useId` **не должен использоваться для создания ключей** в списках. [Ключи должны выбираться на основе данных.](/learn/rendering-lists#where-to-get-your-key)
4848
4949
---
5050
51-
## Usage {/*usage*/}
51+
## Применение {/*usage*/}
5252
5353
<Pitfall>
5454
55-
**Do not call `useId` to generate keys in a list.** [Keys should be generated from your data.](/learn/rendering-lists#where-to-get-your-key)
55+
**Не используйте `useId` для создания ключей** в списках. [Ключи должны выбираться на основе данных.](/learn/rendering-lists#where-to-get-your-key)
5656
5757
</Pitfall>
5858
59-
### Generating unique IDs for accessibility attributes {/*generating-unique-ids-for-accessibility-attributes*/}
59+
### Создание уникальных идентификаторов для атрибутов доступности {/*generating-unique-ids-for-accessibility-attributes*/}
6060
61-
Call `useId` at the top level of your component to generate a unique ID:
61+
Чтобы получить уникальный идентификатор, вызовите `useId` на верхнем уровне своего компонента:
6262
6363
```js [[1, 4, "passwordHintId"]]
6464
import { useId } from 'react';
@@ -68,7 +68,7 @@ function PasswordField() {
6868
// ...
6969
```
7070
71-
You can then pass the <CodeStep step={1}>generated ID</CodeStep> to different attributes:
71+
После чего вы можете указывать этот <CodeStep step={1}> сгенерированный идентификатор</CodeStep> в различных атрибутах:
7272
7373
```js [[1, 2, "passwordHintId"], [1, 3, "passwordHintId"]]
7474
<>
@@ -77,26 +77,26 @@ You can then pass the <CodeStep step={1}>generated ID</CodeStep> to different at
7777
</>
7878
```
7979
80-
**Let's walk through an example to see when this is useful.**
80+
**Разберём на примере, когда это может быть полезно.**
8181
82-
[HTML accessibility attributes](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA) like [`aria-describedby`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-describedby) let you specify that two tags are related to each other. For example, you can specify that an element (like an input) is described by another element (like a paragraph).
82+
[HTML-атрибуты доступности](https://developer.mozilla.org/ru/docs/Web/Accessibility/ARIA), такие как [`aria-describedby`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-describedby), позволяют обозначать смысловую связь между тегами. Например, можно указать, что некоторый элемент разметки (абзац) содержит краткое описание другого элемента (поля ввода).
8383
84-
In regular HTML, you would write it like this:
84+
В обычном HTML вы могли бы описать это так:
8585
8686
```html {5,8}
8787
<label>
88-
Password:
88+
Пароль:
8989
<input
9090
type="password"
9191
aria-describedby="password-hint"
9292
/>
9393
</label>
9494
<p id="password-hint">
95-
The password should contain at least 18 characters
95+
Пароль должен содержать не менее 18 символов
9696
</p>
9797
```
9898
99-
However, hardcoding IDs like this is not a good practice in React. A component may be rendered more than once on the page--but IDs have to be unique! Instead of hardcoding an ID, generate a unique ID with `useId`:
99+
Однако в React подобным образом фиксировать идентификаторы в коде -- не лучшая практика. Один и тот же компонент может использоваться в нескольких разных местах -- но ведь в каждом случае идентификаторы должны быть уникальны! Поэтому вместо фиксированного идентификатора лучше сгенерировать уникальный с помощью `useId`:
100100
101101
```js {4,11,14}
102102
import { useId } from 'react';
@@ -106,21 +106,21 @@ function PasswordField() {
106106
return (
107107
<>
108108
<label>
109-
Password:
109+
Пароль:
110110
<input
111111
type="password"
112112
aria-describedby={passwordHintId}
113113
/>
114114
</label>
115115
<p id={passwordHintId}>
116-
The password should contain at least 18 characters
116+
Пароль должен содержать не менее 18 символов
117117
</p>
118118
</>
119119
);
120120
}
121121
```
122122
123-
Now, even if `PasswordField` appears multiple times on the screen, the generated IDs won't clash.
123+
В итоге, сгенерированные идентификаторы не будут конфликтовать, даже если использовать `PasswordField` на экране в нескольких местах.
124124
125125
<Sandpack>
126126
@@ -132,14 +132,14 @@ function PasswordField() {
132132
return (
133133
<>
134134
<label>
135-
Password:
135+
Пароль:
136136
<input
137137
type="password"
138138
aria-describedby={passwordHintId}
139139
/>
140140
</label>
141141
<p id={passwordHintId}>
142-
The password should contain at least 18 characters
142+
Пароль должен содержать не менее 18 символов
143143
</p>
144144
</>
145145
);
@@ -148,9 +148,9 @@ function PasswordField() {
148148
export default function App() {
149149
return (
150150
<>
151-
<h2>Choose password</h2>
151+
<h2>Выберите пароль</h2>
152152
<PasswordField />
153-
<h2>Confirm password</h2>
153+
<h2>Подтвердите пароль</h2>
154154
<PasswordField />
155155
</>
156156
);
@@ -163,33 +163,33 @@ input { margin: 5px; }
163163
164164
</Sandpack>
165165
166-
[Watch this video](https://www.youtube.com/watch?v=0dNzNcuEuOo) to see the difference in the user experience with assistive technologies.
166+
[Посмотрите видео-демонстрацию](https://www.youtube.com/watch?v=0dNzNcuEuOo) о том, как всё это влияет на опыт использования вспомогательных технологий.
167167
168168
<Pitfall>
169169
170-
With [server rendering](/reference/react-dom/server), **`useId` requires an identical component tree on the server and the client**. If the trees you render on the server and the client don't match exactly, the generated IDs won't match.
170+
При использовании вместе с [серверным рендерингом](/reference/react-dom/server) **`useId` требует, чтобы деревья компонентов на сервере и на клиенте получались идентичными**. Если отрендеренные на сервере и на клиенте деревья не совпадут, то сгенерироованные на сервере идентификаторы не совпадут со сгенерированными на клиенте.
171171
172172
</Pitfall>
173173
174174
<DeepDive>
175175
176-
#### Why is useId better than an incrementing counter? {/*why-is-useid-better-than-an-incrementing-counter*/}
176+
#### Чем `useId` лучше обычного инкрементируемого счётчика? {/*why-is-useid-better-than-an-incrementing-counter*/}
177177
178-
You might be wondering why `useId` is better than incrementing a global variable like `nextId++`.
178+
Возможно, вы задаётесь вопросом, почему для получения нового идентификатора лучше использовать `useId`, а не увеличивать постоянно некий глобальный счётчик -- `nextId++`.
179179
180-
The primary benefit of `useId` is that React ensures that it works with [server rendering.](/reference/react-dom/server) During server rendering, your components generate HTML output. Later, on the client, [hydration](/reference/react-dom/client/hydrateRoot) attaches your event handlers to the generated HTML. For hydration to work, the client output must match the server HTML.
180+
Главное преимущество `useId` в том, что React гарантирует его корректную работу с [серверным рендерингом](/reference/react-dom/server). В процессе серверного рендеринга ваши компоненты создают HTML, к которому затем на клиенте при [гидратации](/reference/react-dom/client/hydrateRoot) подключаются ваши обработчики событий. Чтобы гидратация сработала правильно, клиентский вывод должен совпасть с полученным от сервера HTML.
181181
182-
This is very difficult to guarantee with an incrementing counter because the order in which the client components are hydrated may not match the order in which the server HTML was emitted. By calling `useId`, you ensure that hydration will work, and the output will match between the server and the client.
182+
Однако крайне трудно быть уверенным, что они совпадут, если пользоваться обычным инкрементируемым счётчиком. Ведь порядок гидратации компонентов на клиенте может не совпадать с порядком, в котором HTML составлялся на сервере. Используя же `useId`, вы гарантируете, что созданные идентификаторы на сервере и на клиенте будут совпадать, и гидратация выполнится правильно.
183183
184-
Inside React, `useId` is generated from the "parent path" of the calling component. This is why, if the client and the server tree are the same, the "parent path" will match up regardless of rendering order.
184+
Внутри React `useId` вычисляется на основе "пути из цепочки родителей" того компонента, который вызывает `useId`. А если отрендеренные на сервере и на клиенте деревья компонентов совпадают, то и полный "путь из цепочки родителей" для каждого компонента будет совпадать, в каком бы порядке они не рендерились.
185185
186186
</DeepDive>
187187
188188
---
189189
190-
### Generating IDs for several related elements {/*generating-ids-for-several-related-elements*/}
190+
### Создание идентификаторов для нескольких элементов {/*generating-ids-for-several-related-elements*/}
191191
192-
If you need to give IDs to multiple related elements, you can call `useId` to generate a shared prefix for them:
192+
Если вам нужны разные идентификаторы для нескольких элементов, и эти элементы как-то связаны по смыслу, то с помощью `useId` вы можете создать один общий для всех префикс:
193193
194194
<Sandpack>
195195
@@ -200,10 +200,10 @@ export default function Form() {
200200
const id = useId();
201201
return (
202202
<form>
203-
<label htmlFor={id + '-firstName'}>First Name:</label>
203+
<label htmlFor={id + '-firstName'}>Имя:</label>
204204
<input id={id + '-firstName'} type="text" />
205205
<hr />
206-
<label htmlFor={id + '-lastName'}>Last Name:</label>
206+
<label htmlFor={id + '-lastName'}>Фамилия:</label>
207207
<input id={id + '-lastName'} type="text" />
208208
</form>
209209
);
@@ -216,20 +216,20 @@ input { margin: 5px; }
216216
217217
</Sandpack>
218218
219-
This lets you avoid calling `useId` for every single element that needs a unique ID.
219+
Так можно обойтись без лишних вызовов `useId` на каждый элемент, которому понадобился идентификатор.
220220
221221
---
222222
223-
### Specifying a shared prefix for all generated IDs {/*specifying-a-shared-prefix-for-all-generated-ids*/}
223+
### Задание общего префикса для всех идентификаторов вообще {/*specifying-a-shared-prefix-for-all-generated-ids*/}
224224
225-
If you render multiple independent React applications on a single page, pass `identifierPrefix` as an option to your [`createRoot`](/reference/react-dom/client/createRoot#parameters) or [`hydrateRoot`](/reference/react-dom/client/hydrateRoot) calls. This ensures that the IDs generated by the two different apps never clash because every identifier generated with `useId` will start with the distinct prefix you've specified.
225+
Если вы отображаете несколько независимых React-приложений на одной странице, то в вызовах [`createRoot`](/reference/react-dom/client/createRoot#parameters) и [`hydrateRoot`](/reference/react-dom/client/hydrateRoot) вы можете указать опцию `identifierPrefix`. Поскольку все полученные из `useId` идентификаторы будут с префиксом, указанным в этой опции, то так можно гарантировать, что сгенерированные разными приложениями идентификаторы никогда не пересекутся.
226226
227227
<Sandpack>
228228
229229
```html index.html
230230
<!DOCTYPE html>
231231
<html>
232-
<head><title>My app</title></head>
232+
<head><title>Моё приложение</title></head>
233233
<body>
234234
<div id="root1"></div>
235235
<div id="root2"></div>
@@ -246,14 +246,14 @@ function PasswordField() {
246246
return (
247247
<>
248248
<label>
249-
Password:
249+
Пароль:
250250
<input
251251
type="password"
252252
aria-describedby={passwordHintId}
253253
/>
254254
</label>
255255
<p id={passwordHintId}>
256-
The password should contain at least 18 characters
256+
Пароль должен содержать не менее 18 символов
257257
</p>
258258
</>
259259
);
@@ -262,7 +262,7 @@ function PasswordField() {
262262
export default function App() {
263263
return (
264264
<>
265-
<h2>Choose password</h2>
265+
<h2>Выберите пароль</h2>
266266
<PasswordField />
267267
</>
268268
);

0 commit comments

Comments
 (0)