forked from kay-is/react-from-zero
-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy path12-component-refactor.html
More file actions
138 lines (115 loc) · 4.13 KB
/
12-component-refactor.html
File metadata and controls
138 lines (115 loc) · 4.13 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
<!doctype html>
<title>12 Рефакторинг компонентов - React с нуля</title>
<script src="https://unpkg.com/react@16.4.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.4.0/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/create-react-class@15.6.3/create-react-class.js"></script>
<script src="https://unpkg.com/prop-types@15.6.1/prop-types.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<div id="app"></div>
<script type="text/babel">
// Рефакторинг — это то, что заслуживает внимание React
// Сначала мы поговорим о рефакторинге одного компонента в другой
// если вам повезёт, вы можете просто изменить реализацию компонента
// и не потребуется менять место вызова
// Начнем с компонента, который каким-то образом отрисовывает записи
function ViewBefore(props) {
return (
<table>
<thead>
<tr>
<th>Комната</th>
<th>Люди</th>
</tr>
</thead>
<tbody>
{props.rooms.map(function(room, k) {
return <tr key={k}>
<td>{room.name}</td>
<td>{room.people}</td>
</tr>
})}
</tbody>
</table>
)
}
// У компонента имеет простой интерфейс свойств
ViewBefore.propTypes = {
rooms: PropTypes.array.isRequired,
}
// Теперь мы изменим реализацию на более сложную
function ViewAfter(props) {
return (
<div>
{props.rooms.map(function(room, k) {
var barStyle = {
display: "inline-block",
background: "lightgrey",
width: room.people * 25,
}
return <div key={k}>
{room.people > 0
? <span style={barStyle}>{room.people} людей</span>
: <span>0 людей</span>
}
<span> в комнате {room.name}</span>
</div>
})}
</div>
)
}
// Мы поддерживаем интерфейс свойства идентичным
ViewAfter.propTypes = {
rooms: PropTypes.array.isRequired,
}
// Мы могли бы также сделать компонент более динамичным
var ViewDynamic = createReactClass({
// Мы по-прежнему поддерживаем интерфейс свойств
propTypes: {
rooms: PropTypes.array.isRequired,
},
getInitialState: function() {
return {currentRoom: 0}
},
componentDidMount() {
var component = this
var props = this.props
this.interval = setInterval(function() {
var currentRoom = component.state.currentRoom < props.rooms.length - 1
? component.state.currentRoom + 1
: 0
component.setState({currentRoom: currentRoom})
}, 1000)
},
componentWillUnmount() {
clearInterval(this.interval)
},
render: function() {
var room = this.props.rooms[this.state.currentRoom]
return (
<span style={{color: this.state.color}}>
В комнате <b>{room.name}</b> <b>{room.people}</b> людей.
</span>
)
},
})
// Some data
var rooms = [
{name:"Офис", people: 10},
{name:"Кухня", people: 15},
{name:"Зал заседаний", people: 3},
{name:"Ванная", people: 0},
]
// Как мы видим, компоненты могут использоваться точно так же
// Если мы скопируем реализацию ViewAfter в ViewBefore
// всё будет работать
var reactElement =
<div style={{margin: "auto", width: 500}}>
<h3>До рефакторинга</h3>
<ViewBefore rooms={rooms}/>
<h3>После рефакторинга</h3>
<ViewAfter rooms={rooms}/>
<h3>После рефакторинга с помощью класса компонента</h3>
<ViewDynamic rooms={rooms}/>
</div>
ReactDOM.render(reactElement, document.getElementById("app"))
</script>