Skip to content

Commit da36c13

Browse files
committed
add sum of count
1 parent aa7247d commit da36c13

File tree

2 files changed

+37
-7
lines changed

2 files changed

+37
-7
lines changed

chapter-02/controlpanel_with_summary/src/ControlPanel.js

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,32 @@ const style = {
77

88
class ControlPanel extends Component {
99

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+
1028
render() {
1129
return (
1230
<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>
1636
</div>
1737
);
1838
}

chapter-02/controlpanel_with_summary/src/Counter.js

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,19 @@ class Counter extends Component {
1818
}
1919

2020
onClickIncrementButton() {
21-
this.setState({count: this.state.count + 1});
21+
this.updateCount(true);
2222
}
2323

2424
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)
2634
}
2735

2836
render() {
@@ -39,11 +47,13 @@ class Counter extends Component {
3947

4048
Counter.propTypes = {
4149
caption: PropTypes.string.isRequired,
42-
initValue: PropTypes.number
50+
initValue: PropTypes.number,
51+
onUpdate: PropTypes.func
4352
};
4453

4554
Counter.defaultProps = {
46-
initValue: 0
55+
initValue: 0,
56+
onUpdate: f => f //什么都不做的函数
4757
};
4858

4959
export default Counter;

0 commit comments

Comments
 (0)