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/useId.md
+47-47
Original file line number
Diff line number
Diff line change
@@ -4,7 +4,7 @@ title: useId
4
4
5
5
<Intro>
6
6
7
-
`useId`is a React Hook for generating unique IDs that can be passed to accessibility attributes.
7
+
Хук `useId`позволяет создавать уникальные идентификаторы, которые затем можно использовать, например, в атрибутах доступности.
8
8
9
9
```js
10
10
constid=useId()
@@ -16,11 +16,11 @@ const id = useId()
16
16
17
17
---
18
18
19
-
## Reference {/*reference*/}
19
+
## Справочник {/*reference*/}
20
20
21
21
### `useId()` {/*useid*/}
22
22
23
-
Call `useId` at the top level of your component to generate a unique ID:
23
+
Чтобы создать уникальный идентификатор, вызовите `useId` на верхнем уровне своего компонента:
24
24
25
25
```js
26
26
import { useId } from'react';
@@ -30,35 +30,35 @@ function PasswordField() {
30
30
// ...
31
31
```
32
32
33
-
[See more examples below.](#usage)
33
+
[См. другие примеры ниже.](#usage)
34
34
35
-
#### Parameters {/*parameters*/}
35
+
#### Параметры {/*parameters*/}
36
36
37
-
`useId`does not take any parameters.
37
+
`useId`не принимает параметров.
38
38
39
-
#### Returns {/*returns*/}
39
+
#### Возвращаемое значение {/*returns*/}
40
40
41
-
`useId`returns a unique ID string associated with this particular `useId`call in this particular component.
41
+
`useId`возвращает уникальный идентификатор, привязанный к данному конкретному вызову `useId`в данном конкретном компоненте.
42
42
43
-
#### Caveats {/*caveats*/}
43
+
#### Замечания {/*caveats*/}
44
44
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`-- это хук, поэтому его нужно вызывать только **на верхнем уровне вашего компонента** или хука. Его нельзя вызывать внутри циклов и условий. Если это всё же для чего-то нужно, выделите этот вызов в отдельный компонент, который затем можно рендерить по условию или в цикле.
46
46
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)
48
48
49
49
---
50
50
51
-
## Usage {/*usage*/}
51
+
## Применение {/*usage*/}
52
52
53
53
<Pitfall>
54
54
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)
56
56
57
57
</Pitfall>
58
58
59
-
### Generating unique IDs for accessibility attributes {/*generating-unique-ids-for-accessibility-attributes*/}
59
+
### Создание уникальных идентификаторов для атрибутов доступности {/*generating-unique-ids-for-accessibility-attributes*/}
60
60
61
-
Call `useId` at the top level of your component to generate a unique ID:
61
+
Чтобы получить уникальный идентификатор, вызовите `useId` на верхнем уровне своего компонента:
62
62
63
63
```js [[1, 4, "passwordHintId"]]
64
64
import { useId } from'react';
@@ -68,7 +68,7 @@ function PasswordField() {
68
68
// ...
69
69
```
70
70
71
-
You can then pass the <CodeStep step={1}>generated ID</CodeStep> to different attributes:
71
+
После чего вы можете указывать этот <CodeStep step={1}> сгенерированный идентификатор</CodeStep> в различных атрибутах:
@@ -77,26 +77,26 @@ You can then pass the <CodeStep step={1}>generated ID</CodeStep> to different at
77
77
</>
78
78
```
79
79
80
-
**Let's walk through an example to see when this is useful.**
80
+
**Разберём на примере, когда это может быть полезно.**
81
81
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), позволяют обозначать смысловую связь между тегами. Например, можно указать, что некоторый элемент разметки (абзац) содержит краткое описание другого элемента (поля ввода).
83
83
84
-
In regular HTML, you would write it like this:
84
+
В обычном HTML вы могли бы описать это так:
85
85
86
86
```html {5,8}
87
87
<label>
88
-
Password:
88
+
Пароль:
89
89
<input
90
90
type="password"
91
91
aria-describedby="password-hint"
92
92
/>
93
93
</label>
94
94
<p id="password-hint">
95
-
The password should contain at least 18characters
95
+
Пароль должен содержать не менее 18символов
96
96
</p>
97
97
```
98
98
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`:
100
100
101
101
```js {4,11,14}
102
102
import { useId } from'react';
@@ -106,21 +106,21 @@ function PasswordField() {
106
106
return (
107
107
<>
108
108
<label>
109
-
Password:
109
+
Пароль:
110
110
<input
111
111
type="password"
112
112
aria-describedby={passwordHintId}
113
113
/>
114
114
</label>
115
115
<p id={passwordHintId}>
116
-
The password should contain at least 18characters
116
+
Пароль должен содержать не менее 18символов
117
117
</p>
118
118
</>
119
119
);
120
120
}
121
121
```
122
122
123
-
Now, even if `PasswordField` appears multiple times on the screen, the generated IDs won't clash.
123
+
В итоге, сгенерированные идентификаторы не будут конфликтовать, даже если использовать `PasswordField` на экране в нескольких местах.
124
124
125
125
<Sandpack>
126
126
@@ -132,14 +132,14 @@ function PasswordField() {
132
132
return (
133
133
<>
134
134
<label>
135
-
Password:
135
+
Пароль:
136
136
<input
137
137
type="password"
138
138
aria-describedby={passwordHintId}
139
139
/>
140
140
</label>
141
141
<p id={passwordHintId}>
142
-
The password should contain at least 18characters
142
+
Пароль должен содержать не менее 18символов
143
143
</p>
144
144
</>
145
145
);
@@ -148,9 +148,9 @@ function PasswordField() {
148
148
exportdefaultfunctionApp() {
149
149
return (
150
150
<>
151
-
<h2>Choose password</h2>
151
+
<h2>Выберите пароль</h2>
152
152
<PasswordField />
153
-
<h2>Confirm password</h2>
153
+
<h2>Подтвердите пароль</h2>
154
154
<PasswordField />
155
155
</>
156
156
);
@@ -163,33 +163,33 @@ input { margin: 5px; }
163
163
164
164
</Sandpack>
165
165
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) о том, как всё это влияет на опыт использования вспомогательных технологий.
167
167
168
168
<Pitfall>
169
169
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`требует, чтобы деревья компонентов на сервере и на клиенте получались идентичными**. Если отрендеренные на сервере и на клиенте деревья не совпадут, то сгенерироованные на сервере идентификаторы не совпадут со сгенерированными на клиенте.
171
171
172
172
</Pitfall>
173
173
174
174
<DeepDive>
175
175
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*/}
177
177
178
-
You might be wondering why `useId` is better than incrementing a global variable like`nextId++`.
178
+
Возможно, вы задаётесь вопросом, почему для получения нового идентификатора лучше использовать `useId`, а не увеличивать постоянно некий глобальный счётчик --`nextId++`.
179
179
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.
181
181
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`, вы гарантируете, что созданные идентификаторы на сервере и на клиенте будут совпадать, и гидратация выполнится правильно.
183
183
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`. А если отрендеренные на сервере и на клиенте деревья компонентов совпадают, то и полный "путь из цепочки родителей" для каждого компонента будет совпадать, в каком бы порядке они не рендерились.
185
185
186
186
</DeepDive>
187
187
188
188
---
189
189
190
-
### Generating IDs for several related elements {/*generating-ids-for-several-related-elements*/}
190
+
### Создание идентификаторов для нескольких элементов {/*generating-ids-for-several-related-elements*/}
191
191
192
-
If you need to give IDs to multiple related elements, you can call`useId`to generate a shared prefix for them:
192
+
Если вам нужны разные идентификаторы для нескольких элементов, и эти элементы как-то связаны по смыслу, то с помощью`useId`вы можете создать один общий для всех префикс:
193
193
194
194
<Sandpack>
195
195
@@ -200,10 +200,10 @@ export default function Form() {
This lets you avoid calling `useId`for every single element that needs a unique ID.
219
+
Так можно обойтись без лишних вызовов `useId`на каждый элемент, которому понадобился идентификатор.
220
220
221
221
---
222
222
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*/}
224
224
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` идентификаторы будут с префиксом, указанным в этой опции, то так можно гарантировать, что сгенерированные разными приложениями идентификаторы никогда не пересекутся.
0 commit comments