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
Call`createElement` to create a React element with the given `type`, `props`, and`children`.
24
+
Вызовите`createElement`, чтобы создать React-элемент с указанным `type`, `props` и`children`.
24
25
25
26
```js
26
27
import { createElement } from'react';
@@ -34,44 +35,44 @@ function Greeting({ name }) {
34
35
}
35
36
```
36
37
37
-
[See more examples below.](#usage)
38
+
[См. больше примеров ниже.](#usage)
38
39
39
-
#### Parameters {/*parameters*/}
40
+
#### Параметры {/*parameters*/}
40
41
41
-
*`type`: The`type`argument must be a valid React component type. For example, it could be a tag name string (such as `'div'`or`'span'`), or a React component (a function, a class, or a special component like[`Fragment`](/reference/react/Fragment)).
42
+
*`type`: Аргумент`type`должен быть допустимым типом React-компонента. Например, это может быть строка с именем тега (например, `'div'`или`'span'`) или React-компонент (функция, класс или специальный компонент, такой как[`Fragment`](/reference/react/Fragment)).
42
43
43
-
*`props`: The`props`argument must either be an object or `null`. If you pass`null`, it will be treated the same as an empty object. React will create an element with props matching the `props` you have passed. Note that `ref`and`key`from your `props`object are special and will *not* be available as`element.props.ref`and`element.props.key`on the returned `element`. They will be available as `element.ref`and`element.key`.
44
+
*`props`: Аргумент`props`должен быть либо объектом, либо `null`. Если вы передадите`null`, это будет равносильно передаче пустого объекта. React создаст элемент со свойствами, соответствующими переданным вами `props`. Обратите внимание, что `ref`и`key`из вашего объекта `props`являются специальными и *не* будут доступны как`element.props.ref`и`element.props.key`в возвращаемом `element`. Они будут доступны как `element.ref`и`element.key`.
44
45
45
-
***optional**`...children`: Zero or more child nodes. They can be any React nodes, including React elements, strings, numbers, [portals](/reference/react-dom/createPortal), empty nodes (`null`, `undefined`, `true`, and`false`), and arrays of React nodes.
46
+
***необязательный**`...children`: Ноль или более дочерних узлов. Они могут быть любыми React-узлами, включая React-элементы, строки, числа, [порталы](/reference/react-dom/createPortal), пустые узлы (`null`, `undefined`, `true` и`false`) и массивы React-узлов.
46
47
47
-
#### Returns {/*returns*/}
48
+
#### Возвращает {/*returns*/}
48
49
49
-
`createElement`returns a React element object with a few properties:
50
+
`createElement`возвращает объект React-элемента с несколькими свойствами:
50
51
51
-
*`type`: The `type` you have passed.
52
-
*`props`: The `props` you have passed except for `ref`and`key`.
53
-
*`ref`: The `ref` you have passed. If missing,`null`.
54
-
*`key`: The `key` you have passed, coerced to a string. If missing,`null`.
52
+
*`type`: Переданный вами `type`.
53
+
*`props`: Переданные вами `props`, за исключением `ref`и`key`.
54
+
*`ref`: Переданный вами `ref`. Если отсутствует, то`null`.
55
+
*`key`: Переданный вами `key`, приведенный к строке. Если отсутствует, то`null`.
55
56
56
-
Usually, you'll return the element from your component or make it a child of another element. Although you may read the element's properties, it's best to treat every element as opaque after it's created, and only render it.
57
+
Обычно вы возвращаете элемент из своего компонента или делаете его дочерним элементом другого элемента. Хотя вы можете читать свойства элемента, лучше всего после создания относиться ко всем элементам как к непрозрачным и только рендерить их.
57
58
58
-
#### Caveats {/*caveats*/}
59
+
#### Ограничения {/*caveats*/}
59
60
60
-
*You must**treat React elements and their props as [immutable](https://en.wikipedia.org/wiki/Immutable_object)**and never change their contents after creation. In development, React will [freeze](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze)the returned element and its`props`property shallowly to enforce this.
61
+
*Вы должны**относиться к React-элементам и их props как к [неизменяемым](https://en.wikipedia.org/wiki/Immutable_object)**и никогда не изменять их содержимое после создания. В режиме разработки React будет [замораживать](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze)возвращаемый элемент и его свойство`props`на верхнем уровне, чтобы обеспечить это.
61
62
62
-
*When you use JSX, **you must start a tag with a capital letter to render your own custom component.**In other words, `<Something />`is equivalent to `createElement(Something)`, but`<something />` (lowercase) is equivalent to `createElement('something')` (note it's a string, so it will be treated as a built-in HTML tag).
63
+
*Когда вы используете JSX, **вы должны начинать тег с заглавной буквы, чтобы рендерить собственный пользовательский компонент.**Другими словами, `<Something />`эквивалентно `createElement(Something)`, но`<something />` (строчная буква) эквивалентно `createElement('something')` (обратите внимание, что это строка, поэтому она будет рассматриваться как встроенный HTML-тег).
63
64
64
-
*You should only **pass children as multiple arguments to `createElement`if they are all statically known,**like`createElement('h1', {}, child1, child2, child3)`. If your children are dynamic, pass the entire array as the third argument: `createElement('ul', {}, listItems)`. This ensures that React will [warn you about missing`key`s](/learn/rendering-lists#keeping-list-items-in-order-with-key)for any dynamic lists. For static lists this is not necessary because they never reorder.
65
+
*Вы должны **передавать дочерние элементы в качестве нескольких аргументов `createElement`только в том случае, если они все статически известны,**например`createElement('h1', {}, child1, child2, child3)`. Если ваши дочерние элементы динамические, передайте весь массив в качестве третьего аргумента: `createElement('ul', {}, listItems)`. Это гарантирует, что React [предупредит вас об отсутствующих`key`](/learn/rendering-lists#keeping-list-items-in-order-with-key)для любых динамических списков. Для статических списков это не требуется, так как они никогда не переупорядочиваются.
65
66
66
67
---
67
68
68
-
## Usage {/*usage*/}
69
+
## Использование {/*usage*/}
69
70
70
-
### Creating an element without JSX {/*creating-an-element-without-jsx*/}
71
+
### Создание элемента без JSX {/*creating-an-element-without-jsx*/}
71
72
72
-
If you don't like[JSX](/learn/writing-markup-with-jsx)or can't use it in your project, you can use`createElement`as an alternative.
73
+
Если вам не нравится[JSX](/learn/writing-markup-with-jsx)или вы не можете использовать его в своем проекте, вы можете использовать`createElement`в качестве альтернативы.
73
74
74
-
To create an element without JSX, call`createElement`with some <CodeStepstep={1}>type</CodeStep>, <CodeStepstep={2}>props</CodeStep>, and <CodeStepstep={3}>children</CodeStep>:
75
+
Чтобы создать элемент без JSX, вызовите`createElement`с некоторым <CodeStepstep={1}>типом</CodeStep>, <CodeStepstep={2}>props</CodeStep> и <CodeStepstep={3}>дочерними элементами</CodeStep>:
The <CodeStepstep={3}>children</CodeStep> are optional, and you can pass as many as you need (the example above has three children). This code will display a `<h1>`header with a greeting. For comparison, here is the same example rewritten with JSX:
91
+
<CodeStepstep={3}>Дочерние элементы</CodeStep> необязательны, и вы можете передать столько, сколько вам нужно (в примере выше три дочерних элемента). Этот код отобразит заголовок `<h1>`с приветствием. Для сравнения, вот тот же пример, переписанный с использованием JSX:
@@ -99,23 +100,23 @@ function Greeting({ name }) {
99
100
}
100
101
```
101
102
102
-
To render your own React component, pass a function like`Greeting` as the <CodeStepstep={1}>type</CodeStep> instead of a string like`'h1'`:
103
+
Чтобы рендерить собственный React-компонент, передайте функцию, такую как`Greeting`, в качестве <CodeStepstep={1}>типа</CodeStep> вместо строки, такой как`'h1'`:
Here is a complete example written with`createElement`:
119
+
Вот полный пример, написанный с использованием`createElement`:
119
120
120
121
<Sandpack>
121
122
@@ -149,7 +150,7 @@ export default function App() {
149
150
150
151
</Sandpack>
151
152
152
-
And here is the same example written using JSX:
153
+
А вот тот же пример, написанный с использованием JSX:
153
154
154
155
<Sandpack>
155
156
@@ -176,16 +177,16 @@ export default function App() {
176
177
177
178
</Sandpack>
178
179
179
-
Both coding styles are fine, so you can use whichever one you prefer for your project. The main benefit of using JSX compared to `createElement`is that it's easy to see which closing tag corresponds to which opening tag.
180
+
Оба стиля кодирования подходят, поэтому вы можете использовать тот, который предпочитаете для своего проекта. Основное преимущество использования JSX по сравнению с `createElement`заключается в том, что легко увидеть, какой закрывающий тег соответствует какому открывающему тегу.
180
181
181
182
<DeepDive>
182
183
183
-
#### What is a React element, exactly? {/*what-is-a-react-element-exactly*/}
184
+
#### Что такое React-элемент, собственно? {/*what-is-a-react-element-exactly*/}
184
185
185
-
An element is a lightweight description of a piece of the user interface. For example, both`<Greeting name="Taylor" />` and`createElement(Greeting, { name: 'Taylor' })`produce an object like this:
186
+
Элемент — это легковесное описание части пользовательского интерфейса. Например, и`<Greeting name="Taylor" />`, и`createElement(Greeting, { name: 'Taylor' })`создают объект, подобный этому:
186
187
187
188
```js
188
-
//Slightly simplified
189
+
//Немного упрощенно
189
190
{
190
191
type: Greeting,
191
192
props: {
@@ -196,10 +197,11 @@ An element is a lightweight description of a piece of the user interface. For ex
196
197
}
197
198
```
198
199
199
-
**Note that creating this object does not render the`Greeting`component or create any DOM elements.**
200
+
**Обратите внимание, что создание этого объекта не рендерит компонент`Greeting`и не создает никаких DOM-элементов.**
200
201
201
-
A React element is more like a description--an instruction for React to later render the`Greeting` component. By returning this object from your`App` component, you tell React what to do next.
202
+
React-элемент больше похож на описание — инструкцию для React, чтобы позже отрисовать компонент`Greeting`. Возвращая этот объект из вашего компонента`App`, вы сообщаете React, что делать дальше.
202
203
203
-
Creating elements is extremely cheap so you don't need to try to optimize or avoid it.
204
+
Создание элементов чрезвычайно дешево, поэтому вам не нужно пытаться оптимизировать или избегать этого.
0 commit comments