forked from piotrwitek/react-redux-typescript-guide
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclass-counter.tsx
48 lines (40 loc) · 1.24 KB
/
class-counter.tsx
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
import * as React from 'react';
export type ClassCounterProps = {
className?: string,
style?: React.CSSProperties,
label: string,
initialCount?: number,
};
type State = {
counter: number,
};
export class ClassCounter extends React.Component<ClassCounterProps, State> {
// default props using Property Initializers
static defaultProps: Partial<ClassCounterProps> = {
className: 'default-class',
};
// initial state using Property Initializers
state: State = {
counter: this.props.initialCount || 0,
};
// lifecycle methods should be declared as normal instance methods and it's fine
componentWillReceiveProps({ initialCount }: ClassCounterProps) {
if (initialCount && initialCount !== this.props.initialCount) {
this.setState({ counter: initialCount });
}
}
// handlers using Class Fields with arrow functions
handleIncrement = () => { this.setState({ counter: this.state.counter + 1 }); };
render() {
const { children, label, initialCount, ...restProps } = this.props;
const { counter } = this.state;
return (
<div {...restProps}>
{label}: {counter}
<button type="button" onClick={this.handleIncrement}>
Increment
</button>
</div>
);
}
}