Skip to content

Commit e5e470e

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

1 file changed

Lines changed: 37 additions & 35 deletions

File tree

src/content/reference/react/createElement.md

Lines changed: 37 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
1+
```md
12
---
23
title: createElement
34
---
45

56
<Intro>
67

7-
`createElement` lets you create a React element. It serves as an alternative to writing [JSX.](/learn/writing-markup-with-jsx)
8+
`createElement` позволяет создавать React-элемент. Он служит альтернативой написанию [JSX.](/learn/writing-markup-with-jsx)
89

910
```js
1011
const element = createElement(type, props, ...children)
@@ -16,11 +17,11 @@ const element = createElement(type, props, ...children)
1617

1718
---
1819

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

2122
### `createElement(type, props, ...children)` {/*createelement*/}
2223

23-
Call `createElement` to create a React element with the given `type`, `props`, and `children`.
24+
Вызовите `createElement`, чтобы создать React-элемент с указанным `type`, `props` и `children`.
2425

2526
```js
2627
import { createElement } from 'react';
@@ -34,44 +35,44 @@ function Greeting({ name }) {
3435
}
3536
```
3637

37-
[See more examples below.](#usage)
38+
[См. больше примеров ниже.](#usage)
3839

39-
#### Parameters {/*parameters*/}
40+
#### Параметры {/*parameters*/}
4041

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

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

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-узлов.
4647

47-
#### Returns {/*returns*/}
48+
#### Возвращает {/*returns*/}
4849

49-
`createElement` returns a React element object with a few properties:
50+
`createElement` возвращает объект React-элемента с несколькими свойствами:
5051

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

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+
Обычно вы возвращаете элемент из своего компонента или делаете его дочерним элементом другого элемента. Хотя вы можете читать свойства элемента, лучше всего после создания относиться ко всем элементам как к непрозрачным и только рендерить их.
5758

58-
#### Caveats {/*caveats*/}
59+
#### Ограничения {/*caveats*/}
5960

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` на верхнем уровне, чтобы обеспечить это.
6162

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-тег).
6364

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) для любых динамических списков. Для статических списков это не требуется, так как они никогда не переупорядочиваются.
6566

6667
---
6768

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

70-
### Creating an element without JSX {/*creating-an-element-without-jsx*/}
71+
### Создание элемента без JSX {/*creating-an-element-without-jsx*/}
7172

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` в качестве альтернативы.
7374

74-
To create an element without JSX, call `createElement` with some <CodeStep step={1}>type</CodeStep>, <CodeStep step={2}>props</CodeStep>, and <CodeStep step={3}>children</CodeStep>:
75+
Чтобы создать элемент без JSX, вызовите `createElement` с некоторым <CodeStep step={1}>типом</CodeStep>, <CodeStep step={2}>props</CodeStep> и <CodeStep step={3}>дочерними элементами</CodeStep>:
7576

7677
```js [[1, 5, "'h1'"], [2, 6, "{ className: 'greeting' }"], [3, 7, "'Hello ',"], [3, 8, "createElement('i', null, name),"], [3, 9, "'. Welcome!'"]]
7778
import { createElement } from 'react';
@@ -87,7 +88,7 @@ function Greeting({ name }) {
8788
}
8889
```
8990

90-
The <CodeStep step={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+
<CodeStep step={3}>Дочерние элементы</CodeStep> необязательны, и вы можете передать столько, сколько вам нужно (в примере выше три дочерних элемента). Этот код отобразит заголовок `<h1>` с приветствием. Для сравнения, вот тот же пример, переписанный с использованием JSX:
9192

9293
```js [[1, 3, "h1"], [2, 3, "className=\\"greeting\\""], [3, 4, "Hello <i>{name}</i>. Welcome!"], [1, 5, "h1"]]
9394
function Greeting({ name }) {
@@ -99,23 +100,23 @@ function Greeting({ name }) {
99100
}
100101
```
101102

102-
To render your own React component, pass a function like `Greeting` as the <CodeStep step={1}>type</CodeStep> instead of a string like `'h1'`:
103+
Чтобы рендерить собственный React-компонент, передайте функцию, такую как `Greeting`, в качестве <CodeStep step={1}>типа</CodeStep> вместо строки, такой как `'h1'`:
103104

104105
```js [[1, 2, "Greeting"], [2, 2, "{ name: 'Taylor' }"]]
105106
export default function App() {
106107
return createElement(Greeting, { name: 'Taylor' });
107108
}
108109
```
109110

110-
With JSX, it would look like this:
111+
С JSX это выглядело бы так:
111112

112113
```js [[1, 2, "Greeting"], [2, 2, "name=\\"Taylor\\""]]
113114
export default function App() {
114115
return <Greeting name="Taylor" />;
115116
}
116117
```
117118

118-
Here is a complete example written with `createElement`:
119+
Вот полный пример, написанный с использованием `createElement`:
119120

120121
<Sandpack>
121122

@@ -149,7 +150,7 @@ export default function App() {
149150

150151
</Sandpack>
151152

152-
And here is the same example written using JSX:
153+
А вот тот же пример, написанный с использованием JSX:
153154

154155
<Sandpack>
155156

@@ -176,16 +177,16 @@ export default function App() {
176177

177178
</Sandpack>
178179

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` заключается в том, что легко увидеть, какой закрывающий тег соответствует какому открывающему тегу.
180181

181182
<DeepDive>
182183

183-
#### What is a React element, exactly? {/*what-is-a-react-element-exactly*/}
184+
#### Что такое React-элемент, собственно? {/*what-is-a-react-element-exactly*/}
184185

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' })` создают объект, подобный этому:
186187

187188
```js
188-
// Slightly simplified
189+
// Немного упрощенно
189190
{
190191
type: Greeting,
191192
props: {
@@ -196,10 +197,11 @@ An element is a lightweight description of a piece of the user interface. For ex
196197
}
197198
```
198199

199-
**Note that creating this object does not render the `Greeting` component or create any DOM elements.**
200+
**Обратите внимание, что создание этого объекта не рендерит компонент `Greeting` и не создает никаких DOM-элементов.**
200201

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, что делать дальше.
202203

203-
Creating elements is extremely cheap so you don't need to try to optimize or avoid it.
204+
Создание элементов чрезвычайно дешево, поэтому вам не нужно пытаться оптимизировать или избегать этого.
204205

205206
</DeepDive>
207+
```

0 commit comments

Comments
 (0)