File tree Expand file tree Collapse file tree 2 files changed +37
-7
lines changed
chapter-02/controlpanel_with_summary/src Expand file tree Collapse file tree 2 files changed +37
-7
lines changed Original file line number Diff line number Diff line change @@ -7,12 +7,32 @@ const style = {
7
7
8
8
class ControlPanel extends Component {
9
9
10
+ constructor ( props ) {
11
+ super ( props ) ;
12
+
13
+ this . onCounterUpdate = this . onCounterUpdate . bind ( this ) ;
14
+
15
+ this . initValues = [ 0 , 10 , 20 ] ;
16
+
17
+ const initSum = this . initValues . reduce ( ( a , b ) => a + b , 0 ) ;
18
+ this . state = {
19
+ sum : initSum
20
+ } ;
21
+ }
22
+
23
+ onCounterUpdate ( newValue , previousValue ) {
24
+ const valueChange = newValue - previousValue ;
25
+ this . setState ( { sum : this . state . sum + valueChange } ) ;
26
+ }
27
+
10
28
render ( ) {
11
29
return (
12
30
< div style = { style } >
13
- < Counter caption = "First" />
14
- < Counter caption = "Second" initValue = { 10 } />
15
- < Counter caption = "Third" initValue = { 20 } />
31
+ < Counter onUpdate = { this . onCounterUpdate } caption = "First" />
32
+ < Counter onUpdate = { this . onCounterUpdate } caption = "Second" initValue = { this . initValues [ 1 ] } />
33
+ < Counter onUpdate = { this . onCounterUpdate } caption = "Third" initValue = { this . initValues [ 2 ] } />
34
+ < hr />
35
+ < div > Total Count: { this . state . sum } </ div >
16
36
</ div >
17
37
) ;
18
38
}
Original file line number Diff line number Diff line change @@ -18,11 +18,19 @@ class Counter extends Component {
18
18
}
19
19
20
20
onClickIncrementButton ( ) {
21
- this . setState ( { count : this . state . count + 1 } ) ;
21
+ this . updateCount ( true ) ;
22
22
}
23
23
24
24
onClickDecrementButton ( ) {
25
- this . setState ( { count : this . state . count - 1 } ) ;
25
+ this . updateCount ( false ) ;
26
+ }
27
+
28
+ updateCount ( isIncrement ) {
29
+ const previousValue = this . state . count ;
30
+ const newValue = isIncrement ? previousValue + 1 : previousValue - 1 ;
31
+
32
+ this . setState ( { count : newValue } )
33
+ this . props . onUpdate ( newValue , previousValue )
26
34
}
27
35
28
36
render ( ) {
@@ -39,11 +47,13 @@ class Counter extends Component {
39
47
40
48
Counter . propTypes = {
41
49
caption : PropTypes . string . isRequired ,
42
- initValue : PropTypes . number
50
+ initValue : PropTypes . number ,
51
+ onUpdate : PropTypes . func
43
52
} ;
44
53
45
54
Counter . defaultProps = {
46
- initValue : 0
55
+ initValue : 0 ,
56
+ onUpdate : f => f //什么都不做的函数
47
57
} ;
48
58
49
59
export default Counter ;
You can’t perform that action at this time.
0 commit comments