forked from kay-is/react-from-zero
-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy path06-property-types.html
More file actions
53 lines (41 loc) · 2.37 KB
/
06-property-types.html
File metadata and controls
53 lines (41 loc) · 2.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<!doctype html>
<title>06 Типы свойств - React с нуля</title>
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script src="https://unpkg.com/[email protected]/prop-types.js">
// PropTypes были удалены из React 16 и вынесены в отдельный пакет
</script>
<div id="app"></div>
<script type="text/babel">
// Компоненты создаются для инкапсуляции того, что должно в итоге работать вместе
// из одного места и для повторного использования
// Для повторного использования требуется, чтобы пользователь компонента предоставил правильные свойства,
// чтобы мы могли определить тип каждого свойства и установить значения по умолчанию we
function MyComponent(props) {
return (
<div className={props.className}>
<h1>Привет, </h1>
<h2>{props.customData}</h2>
</div>
)
}
// Добавьте (функцию-)свойство propTypes в функцию-компонент,
// чтобы он мог проверить его свойства (элемента)
MyComponent.propTypes = {
// В React по умолчанию множество типов свойств, например, строка
customData: PropTypes.string,
}
// Добавье (функцию-)свойство defaultProps для установки значений по умолчанию,
// если пользователь ничего не передал
MyComponent.defaultProps = {
customData: "default",
className: "default-class",
}
// Этот компонент отобразит предупреждение в консоли, так как customData должен быть строкой
var reactElement = <MyComponent customData={123}/>
// А этот компонент будет использовать значения по умолчанию
reactElement = <MyComponent/>
var renderTarget = document.getElementById("app")
ReactDOM.render(reactElement, renderTarget)
</script>