Skip to content

Commit 69c7a4d

Browse files
authored
Merge pull request #129 from vvscode/typechecking-with-proptypes
Проверка типов с помощью PropTypes
2 parents fe57aa6 + f3a79fc commit 69c7a4d

File tree

2 files changed

+55
-50
lines changed

2 files changed

+55
-50
lines changed

content/docs/nav.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@
7474
- id: strict-mode
7575
title: Strict Mode
7676
- id: typechecking-with-proptypes
77-
title: Typechecking With PropTypes
77+
title: Проверка типов с помощью PropTypes
7878
- id: uncontrolled-components
7979
title: Uncontrolled Components
8080
- id: web-components
Lines changed: 54 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,26 @@
11
---
22
id: typechecking-with-proptypes
3-
title: Typechecking With PropTypes
3+
title: Проверка типов с помощью PropTypes
44
permalink: docs/typechecking-with-proptypes.html
55
redirect_from:
66
- "docs/react-api.html#typechecking-with-proptypes"
77
---
88

9-
> Note:
9+
> Примечание:
1010
>
11-
> `React.PropTypes` has moved into a different package since React v15.5. Please use [the `prop-types` library instead](https://www.npmjs.com/package/prop-types).
11+
> С версии React 15.5 `React.PropTypes` были вынесены в отдельный пакет. Так что используйте [библиотеку `prop-types`](https://www.npmjs.com/package/prop-types).
1212
>
13-
>We provide [a codemod script](/blog/2017/04/07/react-v15.5.0.html#migrating-from-reactproptypes) to automate the conversion.
13+
> Вы можете использовать [codemod-скрипт](/blog/2017/04/07/react-v15.5.0.html#migrating-from-reactproptypes), чтобы провести замену в коде на использование этой библиотеки.
1414
15-
As your app grows, you can catch a lot of bugs with typechecking. For some applications, you can use JavaScript extensions like [Flow](https://flow.org/) or [TypeScript](https://www.typescriptlang.org/) to typecheck your whole application. But even if you don't use those, React has some built-in typechecking abilities. To run typechecking on the props for a component, you can assign the special `propTypes` property:
15+
По мере роста вашего приложения вы можете отловить много ошибок с помощью проверки типов. Для этого можно использовать расширения JavaScript вроде [Flow](https://flow.org/) и [TypeScript](https://www.typescriptlang.org/). Но, даже если вы ими не пользуетесь, React предоставляет встроенные возможности для проверки типов. Для запуска этой проверки на пропсах компонента вам нужно использовать специальное свойство `propTypes`:
1616

1717
```javascript
1818
import PropTypes from 'prop-types';
1919

2020
class Greeting extends React.Component {
2121
render() {
2222
return (
23-
<h1>Hello, {this.props.name}</h1>
23+
<h1>Привет, {this.props.name}</h1>
2424
);
2525
}
2626
}
@@ -30,18 +30,18 @@ Greeting.propTypes = {
3030
};
3131
```
3232

33-
`PropTypes` exports a range of validators that can be used to make sure the data you receive is valid. In this example, we're using `PropTypes.string`. When an invalid value is provided for a prop, a warning will be shown in the JavaScript console. For performance reasons, `propTypes` is only checked in development mode.
33+
`PropTypes` предоставляет ряд валидаторов, которые могут использоваться для проверки, что получаемые данные корректны. В примере мы использовали `PropTypes.string`. Когда какой-то проп имеет некорректное значение, в консоли будет выведено предупреждение. По соображениям производительности `propTypes` проверяются только в режиме разработки.
3434

3535
### PropTypes {#proptypes}
3636

37-
Here is an example documenting the different validators provided:
37+
Пример использования возможных валидаторов:
3838

3939
```javascript
4040
import PropTypes from 'prop-types';
4141

4242
MyComponent.propTypes = {
43-
// You can declare that a prop is a specific JS type. By default, these
44-
// are all optional.
43+
// Можно объявить проп на соответствиее определённому JS-типу.
44+
// По умолчанию это не обязательно.
4545
optionalArray: PropTypes.array,
4646
optionalBool: PropTypes.bool,
4747
optionalFunc: PropTypes.func,
@@ -50,85 +50,90 @@ MyComponent.propTypes = {
5050
optionalString: PropTypes.string,
5151
optionalSymbol: PropTypes.symbol,
5252

53-
// Anything that can be rendered: numbers, strings, elements or an array
54-
// (or fragment) containing these types.
53+
// Все, что может быть отренедерено:
54+
// числа, строки, элементы или массивы
55+
// (или фрагменты) содержащие эти типы
5556
optionalNode: PropTypes.node,
5657

57-
// A React element.
58+
// React-элемент
5859
optionalElement: PropTypes.element,
5960

60-
// You can also declare that a prop is an instance of a class. This uses
61-
// JS's instanceof operator.
61+
// Можно указать, что проп должен быть экземпляром класса
62+
// Для этого используется оператор `instanceof`.
6263
optionalMessage: PropTypes.instanceOf(Message),
6364

64-
// You can ensure that your prop is limited to specific values by treating
65-
// it as an enum.
65+
// Вы можете задать ограничение конкретными значениями
66+
// при помощи перечисления
6667
optionalEnum: PropTypes.oneOf(['News', 'Photos']),
6768

68-
// An object that could be one of many types
69+
// Объект, одного из нескольких типов
6970
optionalUnion: PropTypes.oneOfType([
7071
PropTypes.string,
7172
PropTypes.number,
7273
PropTypes.instanceOf(Message)
7374
]),
7475

75-
// An array of a certain type
76+
// Массив объектов конкретного типа
7677
optionalArrayOf: PropTypes.arrayOf(PropTypes.number),
7778

78-
// An object with property values of a certain type
79+
// Объект со свойствами конкретного типа
7980
optionalObjectOf: PropTypes.objectOf(PropTypes.number),
8081

81-
// An object taking on a particular shape
82+
// Объект с определенной структурой
8283
optionalObjectWithShape: PropTypes.shape({
8384
color: PropTypes.string,
8485
fontSize: PropTypes.number
8586
}),
8687

87-
// You can chain any of the above with `isRequired` to make sure a warning
88-
// is shown if the prop isn't provided.
88+
// Можно добавить`isRequired` к любому из приведённому выше типу,
89+
// чтобы показывать предупреждение,
90+
// если проп не передан
8991
requiredFunc: PropTypes.func.isRequired,
9092

91-
// A value of any data type
93+
// Значене любого типа
9294
requiredAny: PropTypes.any.isRequired,
9395

94-
// You can also specify a custom validator. It should return an Error
95-
// object if the validation fails. Don't `console.warn` or throw, as this
96-
// won't work inside `oneOfType`.
96+
// Можно добавить собственный валидатор.
97+
// Он должен возращать объект `Error` при ошибке валидации.
98+
// Не используйте `console.warn` или `throw`
99+
// - это не будет работать внутри `oneOfType`
97100
customProp: function(props, propName, componentName) {
98101
if (!/matchme/.test(props[propName])) {
99102
return new Error(
100-
'Invalid prop `' + propName + '` supplied to' +
101-
' `' + componentName + '`. Validation failed.'
103+
'Проп `' + propName + '` компонента' +
104+
' `' + componentName + '` имеет неправильное значение'
102105
);
103106
}
104107
},
105108

106-
// You can also supply a custom validator to `arrayOf` and `objectOf`.
107-
// It should return an Error object if the validation fails. The validator
108-
// will be called for each key in the array or object. The first two
109-
// arguments of the validator are the array or object itself, and the
110-
// current item's key.
109+
// Можно задать свой валидатор для `arrayOf` и `objectOf`.
110+
// Он должен возвращать объект Error при ошибке валидации.
111+
// Валидатор будет вызван для каждого элемента в массиве
112+
// или для каждого свойства объекта.
113+
// Первые два параметра валидатора
114+
// - это массив или объект и ключ текущего элемента
111115
customArrayProp: PropTypes.arrayOf(function(propValue, key, componentName, location, propFullName) {
112116
if (!/matchme/.test(propValue[key])) {
113117
return new Error(
114-
'Invalid prop `' + propFullName + '` supplied to' +
115-
' `' + componentName + '`. Validation failed.'
118+
'Проп `' + propFullName + '` компонента' +
119+
' `' + componentName + '` имеет неправильное значение'
116120
);
117121
}
118122
})
119123
};
120124
```
121125

122-
### Requiring Single Child {#requiring-single-child}
126+
### Ограничение на один дочерний компонент {#requiring-single-child}
123127

124-
With `PropTypes.element` you can specify that only a single child can be passed to a component as children.
128+
С помощью `PropTypes.element` вы можете указать, что в качестве дочернего может быть передан только один элемент.
125129

126130
```javascript
127131
import PropTypes from 'prop-types';
128132

129133
class MyComponent extends React.Component {
130134
render() {
131-
// This must be exactly one element or it will warn.
135+
// Это должен быть ровно один элемент.
136+
// Иначе вы увидете предупреждение
132137
const children = this.props.children;
133138
return (
134139
<div>
@@ -143,45 +148,45 @@ MyComponent.propTypes = {
143148
};
144149
```
145150

146-
### Default Prop Values {#default-prop-values}
151+
### Значения пропсов по умолчанию {#default-prop-values}
147152

148-
You can define default values for your `props` by assigning to the special `defaultProps` property:
153+
Вы можете задать значения по умолчанию для ваших `props` с помощью специального свойства `defaultProps`:
149154

150155
```javascript
151156
class Greeting extends React.Component {
152157
render() {
153158
return (
154-
<h1>Hello, {this.props.name}</h1>
159+
<h1>Привет, {this.props.name}</h1>
155160
);
156161
}
157162
}
158163

159-
// Specifies the default values for props:
164+
// Задание значений по умолчанию для пропсов:
160165
Greeting.defaultProps = {
161-
name: 'Stranger'
166+
name: 'Незнакомец'
162167
};
163168

164-
// Renders "Hello, Stranger":
169+
// Отрендерит "Привет, Незнакомец":
165170
ReactDOM.render(
166171
<Greeting />,
167172
document.getElementById('example')
168173
);
169174
```
170175

171-
If you are using a Babel transform like [transform-class-properties](https://babeljs.io/docs/plugins/transform-class-properties/) , you can also declare `defaultProps` as static property within a React component class. This syntax has not yet been finalized though and will require a compilation step to work within a browser. For more information, see the [class fields proposal](https://github.com/tc39/proposal-class-fields).
176+
Если вы используете один из Babel-плагинов по преобразованию кода, вроде [transform-class-properties](https://babeljs.io/docs/plugins/transform-class-properties/), то можете объявить `defaultProps` как статическое свойство класса (для компонента-наследника от `React.Component`). Этот синтаксис еще не утвержден, так что для его работы в браузере нужна компиляция. Подробнее смотрите в [предложении о полях класса](https://github.com/tc39/proposal-class-fields).
172177

173178
```javascript
174179
class Greeting extends React.Component {
175180
static defaultProps = {
176-
name: 'stranger'
181+
name: 'незнакомец'
177182
}
178183

179184
render() {
180185
return (
181-
<div>Hello, {this.props.name}</div>
186+
<div>Привет, {this.props.name}</div>
182187
)
183188
}
184189
}
185190
```
186191

187-
The `defaultProps` will be used to ensure that `this.props.name` will have a value if it was not specified by the parent component. The `propTypes` typechecking happens after `defaultProps` are resolved, so typechecking will also apply to the `defaultProps`.
192+
Определение `defaultProps` гарантирует, что `this.props.name` будет иметь значение, даже если оно не было указано родительским компонентом. Сначала применяются значения по умолчанию, заданные в `defaultProps`. После запускается проверка типов с помощью `propTypes`. Так что проверка типов распространяется и на значения по умолчанию.

0 commit comments

Comments
 (0)