Skip to content

Commit 2571281

Browse files
authored
Translate "Components and Props" into Russian (#34)
* Компоненты и пропсы * тэг => тег * review round 1 * drop * fix * review round 3
1 parent c59adc9 commit 2571281

File tree

2 files changed

+54
-52
lines changed

2 files changed

+54
-52
lines changed

content/docs/components-and-props.md

Lines changed: 53 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
---
22
id: components-and-props
3-
title: Components and Props
3+
title: Компоненты и пропсы
44
permalink: docs/components-and-props.html
55
redirect_from:
66
- "docs/reusable-components.html"
@@ -16,23 +16,23 @@ prev: rendering-elements.html
1616
next: state-and-lifecycle.html
1717
---
1818

19-
Components let you split the UI into independent, reusable pieces, and think about each piece in isolation. This page provides an introduction to the idea of components. You can find a [detailed component API reference here](/docs/react-component.html).
19+
Компоненты позволяют разбить интерфейс на независимые части, про которые легко думать в отдельности. Их можно складывать вместе и использовать несколько раз. На этой странице мы ознакомимся с самой идеей компонентов — [детальное описание API находится здесь](/docs/react-component.html).
2020

21-
Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called "props") and return React elements describing what should appear on the screen.
21+
Во многом компоненты ведут себя как обычные функции JavaScript. Они принимают произвольные входные данные (так называемые «пропсы») и возвращают React-элементы, описывающие, что мы хотим увидеть на экране.
2222

23-
## Function and Class Components {#function-and-class-components}
23+
## Функциональные и классовые компоненты {#function-and-class-components}
2424

25-
The simplest way to define a component is to write a JavaScript function:
25+
Проще всего объявить React-компонент как функцию:
2626

2727
```js
2828
function Welcome(props) {
2929
return <h1>Hello, {props.name}</h1>;
3030
}
3131
```
3232

33-
This function is a valid React component because it accepts a single "props" (which stands for properties) object argument with data and returns a React element. We call such components "function components" because they are literally JavaScript functions.
33+
Эта функция — компонент, потому что она получает данные в одном объекте («пропсы») в качестве параметра и возвращает React-элемент. Мы будем называть такие компоненты «функциональными», так как они буквально являются функциями.
3434

35-
You can also use an [ES6 class](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes) to define a component:
35+
Ещё компоненты можно определять как [классы ES6](https://developer.mozilla.org/ru-RU/docs/Web/JavaScript/Reference/Classes):
3636

3737
```js
3838
class Welcome extends React.Component {
@@ -42,34 +42,34 @@ class Welcome extends React.Component {
4242
}
4343
```
4444

45-
The above two components are equivalent from React's point of view.
45+
С точки зрения React, эти два компонента эквивалентны.
4646

47-
Classes have some additional features that we will discuss in the [next sections](/docs/state-and-lifecycle.html). Until then, we will use function components for their conciseness.
47+
Классам доступны дополнительные возможности, о которых мы поговорим в [следующих главах](/docs/state-and-lifecycle.html). Но пока что мы предпочтём функции за их краткость.
4848

49-
## Rendering a Component {#rendering-a-component}
49+
## Как отрендерить компонент {#rendering-a-component}
5050

51-
Previously, we only encountered React elements that represent DOM tags:
51+
Пока что мы только встречали React-элементы, представляющие собой DOM-теги:
5252

5353
```js
5454
const element = <div />;
5555
```
5656

57-
However, elements can also represent user-defined components:
57+
Но элементы могут описывать и наши собственные компоненты:
5858

5959
```js
60-
const element = <Welcome name="Sara" />;
60+
const element = <Welcome name="Алиса" />;
6161
```
6262

63-
When React sees an element representing a user-defined component, it passes JSX attributes to this component as a single object. We call this object "props".
63+
Когда React встречает подобный элемент, он собирает все JSX-атрибуты в один объект и передаёт их нашему компоненту. Этот объект называется «пропсы» (props).
6464

65-
For example, this code renders "Hello, Sara" on the page:
65+
Например, этот компонент выведет «Привет, Алиса» на страницу:
6666

6767
```js{1,5}
6868
function Welcome(props) {
69-
return <h1>Hello, {props.name}</h1>;
69+
return <h1>Привет, {props.name}</h1>;
7070
}
7171
72-
const element = <Welcome name="Sara" />;
72+
const element = <Welcome name="Алиса" />;
7373
ReactDOM.render(
7474
element,
7575
document.getElementById('root')
@@ -78,24 +78,24 @@ ReactDOM.render(
7878

7979
[](codepen://components-and-props/rendering-a-component)
8080

81-
Let's recap what happens in this example:
81+
Давайте разберём, что именно здесь происходит:
8282

83-
1. We call `ReactDOM.render()` with the `<Welcome name="Sara" />` element.
84-
2. React calls the `Welcome` component with `{name: 'Sara'}` as the props.
85-
3. Our `Welcome` component returns a `<h1>Hello, Sara</h1>` element as the result.
86-
4. React DOM efficiently updates the DOM to match `<h1>Hello, Sara</h1>`.
83+
1. Мы передаём React-элемент `<Welcome name="Алиса" />` в `ReactDOM.render()`.
84+
2. React вызывает наш компонент `Welcome` с пропсами `{name: 'Алиса'}`.
85+
3. Наш компонент `Welcome` возвращает элемент `<h1>Привет, Алиса</h1>` в качестве результата.
86+
4. React DOM делает минимальные изменения в DOM, чтобы получилось `<h1>Привет, Алиса</h1>`.
8787

88-
>**Note:** Always start component names with a capital letter.
88+
>**Примечание:** Всегда называйте компоненты с заглавной буквы.
8989
>
90-
>React treats components starting with lowercase letters as DOM tags. For example, `<div />` represents an HTML div tag, but `<Welcome />` represents a component and requires `Welcome` to be in scope.
90+
>Если компонент начинается с маленькой буквы, React принимает его за DOM-тег. Например, `<div />` это div-тег из HTML, а `<Welcome />` это уже наш компонент `Welcome`, который должен быть в области видимости.
9191
>
92-
>You can read more about the reasoning behind this convention [here.](/docs/jsx-in-depth.html#user-defined-components-must-be-capitalized)
92+
>Вы можете почитать, почему это так работает [здесь.](/docs/jsx-in-depth.html#user-defined-components-must-be-capitalized)
9393
94-
## Composing Components {#composing-components}
94+
## Композиция компонентов {#composing-components}
9595

96-
Components can refer to other components in their output. This lets us use the same component abstraction for any level of detail. A button, a form, a dialog, a screen: in React apps, all those are commonly expressed as components.
96+
Компоненты могут ссылаться на другие компоненты в возвращённом ими дереве. Это позволяет нам использовать одну и ту же абстракцию — компоненты — на любом уровне нашего приложения. Неважно, пишем ли мы кнопку, форму или целый экран: все они, как правило, представляют собой компоненты в React-приложениях.
9797

98-
For example, we can create an `App` component that renders `Welcome` many times:
98+
Например, компонент `App` может отрендерить компонент `Welcome` несколько раз:
9999

100100
```js{8-10}
101101
function Welcome(props) {
@@ -105,9 +105,9 @@ function Welcome(props) {
105105
function App() {
106106
return (
107107
<div>
108-
<Welcome name="Sara" />
109-
<Welcome name="Cahal" />
110-
<Welcome name="Edite" />
108+
<Welcome name="Алиса" />
109+
<Welcome name="Базилио" />
110+
<Welcome name="Буратино" />
111111
</div>
112112
);
113113
}
@@ -120,13 +120,13 @@ ReactDOM.render(
120120

121121
[](codepen://components-and-props/composing-components)
122122

123-
Typically, new React apps have a single `App` component at the very top. However, if you integrate React into an existing app, you might start bottom-up with a small component like `Button` and gradually work your way to the top of the view hierarchy.
123+
В приложениях, написанных на React с нуля, как правило, есть один компонент `App`, который находится на самом верху. В случае, если вы переписываете существующее приложение на React, имеет смысл начать работу с маленького компонента типа `Button` и постепенно двигаться «вверх» по иерархии.
124124

125-
## Extracting Components {#extracting-components}
125+
## Извлечение компонентов {#extracting-components}
126126

127-
Don't be afraid to split components into smaller components.
127+
Не бойтесь разбивать компоненты на части.
128128

129-
For example, consider this `Comment` component:
129+
Допустим, у нас есть компонент `Comment`:
130130

131131
```js
132132
function Comment(props) {
@@ -154,11 +154,11 @@ function Comment(props) {
154154

155155
[](codepen://components-and-props/extracting-components)
156156

157-
It accepts `author` (an object), `text` (a string), and `date` (a date) as props, and describes a comment on a social media website.
157+
Этот компонент представляет собой комментарий в социальной сети. Его пропсы включают в себя `author` (объект), `text` (строка), и `date` (дата).
158158

159-
This component can be tricky to change because of all the nesting, and it is also hard to reuse individual parts of it. Let's extract a few components from it.
159+
С этим компонентом может быть не очень удобно работать из-за излишней вложенности. Мы также не можем повторно использовать его составные части. Давайте извлечём из него пару компонентов.
160160

161-
First, we will extract `Avatar`:
161+
Для начала извлечём `Avatar`:
162162

163163
```js{3-6}
164164
function Avatar(props) {
@@ -171,11 +171,11 @@ function Avatar(props) {
171171
}
172172
```
173173

174-
The `Avatar` doesn't need to know that it is being rendered inside a `Comment`. This is why we have given its prop a more generic name: `user` rather than `author`.
174+
Компоненту `Avatar` незачем знать, что он рендерится внутри `Comment`. Поэтому мы дали его пропу чуть менее конкретное имя — `user`, а не `author`.
175175

176-
We recommend naming props from the component's own point of view rather than the context in which it is being used.
176+
Пропсы следует называть так, чтобы они имели смысл в первую очередь с точки зрения самого компонента, а уже во вторую тех компонентов, которые его рендерят.
177177

178-
We can now simplify `Comment` a tiny bit:
178+
Теперь можно немножко упростить наш `Comment`:
179179

180180
```js{5}
181181
function Comment(props) {
@@ -198,7 +198,7 @@ function Comment(props) {
198198
}
199199
```
200200

201-
Next, we will extract a `UserInfo` component that renders an `Avatar` next to the user's name:
201+
Следующим шагом извлечём компонент `UserInfo`, который рендерит `Avatar` рядом с именем пользователя:
202202

203203
```js{3-8}
204204
function UserInfo(props) {
@@ -213,7 +213,7 @@ function UserInfo(props) {
213213
}
214214
```
215215

216-
This lets us simplify `Comment` even further:
216+
Это позволит ещё сильнее упростить `Comment`:
217217

218218
```js{4}
219219
function Comment(props) {
@@ -233,30 +233,32 @@ function Comment(props) {
233233

234234
[](codepen://components-and-props/extracting-components-continued)
235235

236-
Extracting components might seem like grunt work at first, but having a palette of reusable components pays off in larger apps. A good rule of thumb is that if a part of your UI is used several times (`Button`, `Panel`, `Avatar`), or is complex enough on its own (`App`, `FeedStory`, `Comment`), it is a good candidate to be a reusable component.
236+
Извлечение компонентов может сначала показаться неблагодарной работой. Тем не менее, в больших приложениях очень полезно иметь палитру компонентов, которые можно многократно использовать. Если вы не уверены, извлекать компонент или нет, вот простое правило. Если какая-то часть интерфейса многократно в нём повторяется (`Button`, `Panel`, `Avatar`) или сама по себе достаточно сложная (`App`, `FeedStory`, `Comment`), имеет смысл её вынести в независимый компонент.
237+
238+
## Пропсы можно только читать {#props-are-read-only}
237239

238-
## Props are Read-Only {#props-are-read-only}
240+
Компонент никогда не должен что-то записывать в свои пропсы — вне зависимости от того, [функциональный он или классовый](#function-and-class-components).
239241

240-
Whether you declare a component [as a function or a class](#function-and-class-components), it must never modify its own props. Consider this `sum` function:
242+
Возьмём для примера функцию `sum`:
241243

242244
```js
243245
function sum(a, b) {
244246
return a + b;
245247
}
246248
```
247249

248-
Such functions are called ["pure"](https://en.wikipedia.org/wiki/Pure_function) because they do not attempt to change their inputs, and always return the same result for the same inputs.
250+
Такие функции называют [«чистыми»](https://ru.wikipedia.org/wiki/%D0%A7%D0%B8%D1%81%D1%82%D0%BE%D1%82%D0%B0_%D1%84%D1%83%D0%BD%D0%BA%D1%86%D0%B8%D0%B8), потому что они не меняют свои входные данные и предсказуемо возвращают один и тот же результат для одинаковых аргументов.
249251

250-
In contrast, this function is impure because it changes its own input:
252+
А вот пример нечистой функции — она записывает данные в свои же аргументы:
251253

252254
```js
253255
function withdraw(account, amount) {
254256
account.total -= amount;
255257
}
256258
```
257259

258-
React is pretty flexible but it has a single strict rule:
260+
React достаточно гибкий, но есть одно правило, которое нельзя нарушать:
259261

260-
**All React components must act like pure functions with respect to their props.**
262+
**React-компоненты обязаны вести себя как чистые функции по отношению к своим пропсам.**
261263

262-
Of course, application UIs are dynamic and change over time. In the [next section](/docs/state-and-lifecycle.html), we will introduce a new concept of "state". State allows React components to change their output over time in response to user actions, network responses, and anything else, without violating this rule.
264+
Конечно, интерфейсы приложений обычно изменяются с течением времени. В [следующей главе](/docs/state-and-lifecycle.html) мы узнаем о том, что такое «состояние» компонента. Состояние даёт компонентам возможность реагировать на действия пользователя, ответы сервера и другие события, не нарушая чистоту компонента.

content/docs/nav.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
- id: rendering-elements
1919
title: Rendering Elements
2020
- id: components-and-props
21-
title: Components and Props
21+
title: Компоненты и пропсы
2222
- id: state-and-lifecycle
2323
title: State and Lifecycle
2424
- id: handling-events

0 commit comments

Comments
 (0)