Skip to content

Commit f197849

Browse files
committed
Merge branch 'master' into docs/refs-and-the-dom
2 parents 6c1acd4 + 83e798d commit f197849

File tree

11 files changed

+386
-369
lines changed

11 files changed

+386
-369
lines changed

TRANSLATION.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,7 @@ React elements are [immutable](https://en.wikipedia.org/wiki/Immutable_object).
175175
| bind | привязка |
176176
| bug | баг, дефект |
177177
| bundler | бандлер |
178+
| cache | кеш |
178179
| callback | колбэк |
179180
| camelCase | *camelCase* |
180181
| child | дочерний |

content/docs/composition-vs-inheritance.md

Lines changed: 30 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,22 @@
11
---
22
id: composition-vs-inheritance
3-
title: Composition vs Inheritance
3+
title: Композиция против наследования
44
permalink: docs/composition-vs-inheritance.html
55
redirect_from:
66
- "docs/multiple-components.html"
77
prev: lifting-state-up.html
88
next: thinking-in-react.html
99
---
1010

11-
React has a powerful composition model, and we recommend using composition instead of inheritance to reuse code between components.
11+
React имеет мощную модель композиции, поэтому для переиспользования кода между компонентами мы рекомендуем использовать композицию вместо наследования.
1212

13-
In this section, we will consider a few problems where developers new to React often reach for inheritance, and show how we can solve them with composition.
13+
В этой главе мы рассмотрим несколько проблем, которые новички в React решают наследованием и попробуем решить их с помощью композиции.
1414

15-
## Containment {#containment}
15+
## Вставка {#containment}
1616

17-
Some components don't know their children ahead of time. This is especially common for components like `Sidebar` or `Dialog` that represent generic "boxes".
17+
Некоторые компоненты не знают своих потомков заранее. Это особенно характерно для таких компонентов, как `Sidebar` или `Dialog`, которые представляют из себя как бы «коробку», в которую можно что-то положить.
1818

19-
We recommend that such components use the special `children` prop to pass children elements directly into their output:
19+
Для таких компонентов мы рекомендуем использовать специальный проп `children`, который передаст дочерние элементы сразу на вывод:
2020

2121
```js{4}
2222
function FancyBorder(props) {
@@ -28,28 +28,28 @@ function FancyBorder(props) {
2828
}
2929
```
3030

31-
This lets other components pass arbitrary children to them by nesting the JSX:
31+
Это позволит передать компоненту произвольные дочерние элементы, вложив их в JSX:
3232

3333
```js{4-9}
3434
function WelcomeDialog() {
3535
return (
3636
<FancyBorder color="blue">
3737
<h1 className="Dialog-title">
38-
Welcome
38+
Добро пожаловать
3939
</h1>
4040
<p className="Dialog-message">
41-
Thank you for visiting our spacecraft!
41+
Спасибо, что посетили наш космический корабль!
4242
</p>
4343
</FancyBorder>
4444
);
4545
}
4646
```
4747

48-
**[Try it on CodePen](https://codepen.io/gaearon/pen/ozqNOV?editors=0010)**
48+
**[Посмотреть на CodePen](https://codepen.io/gaearon/pen/ozqNOV?editors=0010)**
4949

50-
Anything inside the `<FancyBorder>` JSX tag gets passed into the `FancyBorder` component as a `children` prop. Since `FancyBorder` renders `{props.children}` inside a `<div>`, the passed elements appear in the final output.
50+
Всё, что находится внутри JSX-тега `<FancyBorder>`, передаётся в компонент `FancyBorder` через проп `children`. Поскольку `FancyBorder` рендерит `{props.children}` внутри `<div>`, все переданные элементы отображаются в конечном выводе.
5151

52-
While this is less common, sometimes you might need multiple "holes" in a component. In such cases you may come up with your own convention instead of using `children`:
52+
Иногда в компоненте необходимо иметь несколько мест для вставки. В таком случае можно придумать свой формат, а не использовать `children`:
5353

5454
```js{5,8,18,21}
5555
function SplitPane(props) {
@@ -78,15 +78,15 @@ function App() {
7878
}
7979
```
8080

81-
[**Try it on CodePen**](https://codepen.io/gaearon/pen/gwZOJp?editors=0010)
81+
[**Посмотреть на CodePen**](https://codepen.io/gaearon/pen/gwZOJp?editors=0010)
8282

83-
React elements like `<Contacts />` and `<Chat />` are just objects, so you can pass them as props like any other data. This approach may remind you of "slots" in other libraries but there are no limitations on what you can pass as props in React.
83+
Такие React-элементы, как `<Contacts />` и `<Chat />` являются просто объектами, поэтому их можно передать в виде пропсов, как и любые другие данные. Этот подход может напоминать понятие «слотов» в других библиотеках, однако, в React нет никаких ограничений на то, что можно передать в качестве пропсов.
8484

85-
## Specialization {#specialization}
85+
## Специализация {#specialization}
8686

87-
Sometimes we think about components as being "special cases" of other components. For example, we might say that a `WelcomeDialog` is a special case of `Dialog`.
87+
Некоторые компоненты можно рассматривать как «частные случаи» других компонентов. Например, `WelcomeDialog` может быть частным случаем `Dialog`.
8888

89-
In React, this is also achieved by composition, where a more "specific" component renders a more "generic" one and configures it with props:
89+
В React это можно сделать через композицию, где «частный» вариант компонента рендерит более «общий» и настраивает его с помощью пропсов:
9090

9191
```js{5,8,16-18}
9292
function Dialog(props) {
@@ -105,15 +105,15 @@ function Dialog(props) {
105105
function WelcomeDialog() {
106106
return (
107107
<Dialog
108-
title="Welcome"
109-
message="Thank you for visiting our spacecraft!" />
108+
title="Добро пожаловать"
109+
message="Спасибо, что посетили наш космический корабль!" />
110110
);
111111
}
112112
```
113113

114-
[**Try it on CodePen**](https://codepen.io/gaearon/pen/kkEaOZ?editors=0010)
114+
[**Посмотреть на CodePen**](https://codepen.io/gaearon/pen/kkEaOZ?editors=0010)
115115

116-
Composition works equally well for components defined as classes:
116+
Композиция хорошо работает и для компонентов, определённых через классы:
117117

118118
```js{10,27-31}
119119
function Dialog(props) {
@@ -140,12 +140,12 @@ class SignUpDialog extends React.Component {
140140
141141
render() {
142142
return (
143-
<Dialog title="Mars Exploration Program"
144-
message="How should we refer to you?">
143+
<Dialog title="Программа исследования Марса"
144+
message="Как к вам обращаться?">
145145
<input value={this.state.login}
146146
onChange={this.handleChange} />
147147
<button onClick={this.handleSignUp}>
148-
Sign Me Up!
148+
Запишите меня!
149149
</button>
150150
</Dialog>
151151
);
@@ -156,17 +156,17 @@ class SignUpDialog extends React.Component {
156156
}
157157
158158
handleSignUp() {
159-
alert(`Welcome aboard, ${this.state.login}!`);
159+
alert(`Добро пожаловать на борт, ${this.state.login}!`);
160160
}
161161
}
162162
```
163163

164-
[**Try it on CodePen**](https://codepen.io/gaearon/pen/gwZbYa?editors=0010)
164+
[**Посмотреть на CodePen**](https://codepen.io/gaearon/pen/gwZbYa?editors=0010)
165165

166-
## So What About Inheritance? {#so-what-about-inheritance}
166+
## Так что насчёт наследования? {#so-what-about-inheritance}
167167

168-
At Facebook, we use React in thousands of components, and we haven't found any use cases where we would recommend creating component inheritance hierarchies.
168+
В Facebook мы используем React в тысячах компонентов, и не находили случаев, когда бы рекомендовали создавать иерархии наследования компонентов.
169169

170-
Props and composition give you all the flexibility you need to customize a component's look and behavior in an explicit and safe way. Remember that components may accept arbitrary props, including primitive values, React elements, or functions.
170+
Пропсы и композиция дают вам всю гибкость, необходимую для настройки внешнего вида и поведения компонента явным и безопасным способом. Помните, что компоненты могут принимать произвольные пропсы, включая примитивные значения, React-элементы или функции.
171171

172-
If you want to reuse non-UI functionality between components, we suggest extracting it into a separate JavaScript module. The components may import it and use that function, object, or a class, without extending it.
172+
Если вы хотите переиспользовать не связанную с внешним видом функциональность между компонентами, извлеките её в отдельный JavaScript-модуль. Импортируйте его в компонент и используйте эту функцию, объект или класс, не расширяя их.

content/docs/nav.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@
7878
- id: uncontrolled-components
7979
title: Неконтролируемые компоненты
8080
- id: web-components
81-
title: Web Components
81+
title: Веб-компоненты
8282
- title: Справочник API
8383
items:
8484
- id: react-api

content/docs/web-components.md

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,46 @@
11
---
22
id: web-components
3-
title: Web Components
3+
title: Веб-компоненты
44
permalink: docs/web-components.html
55
redirect_from:
66
- "docs/webcomponents.html"
77
---
88

9-
React and [Web Components](https://developer.mozilla.org/en-US/docs/Web/Web_Components) are built to solve different problems. Web Components provide strong encapsulation for reusable components, while React provides a declarative library that keeps the DOM in sync with your data. The two goals are complementary. As a developer, you are free to use React in your Web Components, or to use Web Components in React, or both.
9+
React и [веб-компоненты](https://developer.mozilla.org/ru/docs/Web/Web_Components) созданы для решения самых разных задач. Веб-компоненты обеспечивают надёжную инкапсуляцию для повторно используемых компонентов, в то время как React предоставляет декларативную библиотеку для синхронизации данных c DOM. Две цели дополняют друг друга. Как разработчик, вы можете использовать React в своих веб-компонентах, или использовать веб-компоненты в React, или и то, и другое.
1010

11-
Most people who use React don't use Web Components, but you may want to, especially if you are using third-party UI components that are written using Web Components.
11+
Большинство разработчиков React обходятся без веб-компонентов, но у вас может появиться желание попробовать их. Например, если ваш проект использует сторонние компоненты пользовательского интерфейса, написанные с помощью веб-компонентов.
1212

13-
## Using Web Components in React {#using-web-components-in-react}
13+
## Использование веб-компонентов в React {#using-web-components-in-react}
1414

1515
```javascript
1616
class HelloMessage extends React.Component {
1717
render() {
18-
return <div>Hello <x-search>{this.props.name}</x-search>!</div>;
18+
return <div>Привет, <x-search>{this.props.name}</x-search>!</div>;
1919
}
2020
}
2121
```
2222

23-
> Note:
23+
> Примечание:
2424
>
25-
> Web Components often expose an imperative API. For instance, a `video` Web Component might expose `play()` and `pause()` functions. To access the imperative APIs of a Web Component, you will need to use a ref to interact with the DOM node directly. If you are using third-party Web Components, the best solution is to write a React component that behaves as a wrapper for your Web Component.
25+
> Веб-компоненты часто предоставляют императивный API. Например, веб-компонент `video` может предоставлять функции `play()` и `pause()`. Чтобы получить доступ к необходимому API веб-компонентов, необходимо использовать реф для взаимодействия с DOM-узлом напрямую. Если вы используете сторонние веб-компоненты, лучшим решением будет создать React-компонент и использовать его как обёртку для веб-компонента.
2626
>
27-
> Events emitted by a Web Component may not properly propagate through a React render tree.
28-
> You will need to manually attach event handlers to handle these events within your React components.
27+
> События, созданные веб-компонентами, могут неправильно распостраняться через дерево React-компонентов.
28+
> Вам нужно вручную добавить обработчики для таких событий в собственные React-компоненты.
2929
30-
One common confusion is that Web Components use "class" instead of "className".
30+
Одно из распространённых заблуждений — это то, что в веб-компонентах используется «class» вместо «className».
3131

3232
```javascript
3333
function BrickFlipbox() {
3434
return (
3535
<brick-flipbox class="demo">
36-
<div>front</div>
37-
<div>back</div>
36+
<div>Передняя сторона</div>
37+
<div>Обратная сторона</div>
3838
</brick-flipbox>
3939
);
4040
}
4141
```
4242

43-
## Using React in your Web Components {#using-react-in-your-web-components}
43+
## Использование React в веб-компонентах {#using-react-in-your-web-components}
4444

4545
```javascript
4646
class XSearch extends HTMLElement {
@@ -56,7 +56,7 @@ class XSearch extends HTMLElement {
5656
customElements.define('x-search', XSearch);
5757
```
5858

59-
>Note:
59+
>Примечание:
6060
>
61-
>This code **will not** work if you transform classes with Babel. See [this issue](https://github.com/w3c/webcomponents/issues/587) for the discussion.
62-
>Include the [custom-elements-es5-adapter](https://github.com/webcomponents/webcomponentsjs#custom-elements-es5-adapterjs) before you load your web components to fix this issue.
61+
>Данный код **не будет** работать, если вы преобразуете классы с помощью Babel. Взгляните на [ишью](https://github.com/w3c/webcomponents/issues/587) с обсуждением.
62+
>Добавьте шим [custom-elements-es5-adapter](https://github.com/webcomponents/webcomponentsjs#custom-elements-es5-adapterjs) перед загрузкой веб-компонентов, чтобы решить эту проблему.

content/languages.yml

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@
4242
- name: French
4343
translated_name: Français
4444
code: fr
45-
status: 1
45+
status: 2
4646
- name: Gujarati
4747
translated_name: ગુજરાતી
4848
code: gu
@@ -123,6 +123,9 @@
123123
translated_name: සිංහල
124124
code: si
125125
status: 0
126+
- name: Swedish
127+
translated_name: Svenska
128+
code: sv
126129
- name: Tamil
127130
translated_name: தமிழ்
128131
code: ta
@@ -158,4 +161,4 @@
158161
- name: Traditional Chinese
159162
translated_name: 繁體中文
160163
code: zh-hant
161-
status: 0
164+
status: 0

0 commit comments

Comments
 (0)