-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.tsx
More file actions
131 lines (114 loc) · 2.6 KB
/
Copy pathApp.tsx
File metadata and controls
131 lines (114 loc) · 2.6 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
import * as React from 'react';
import './App.css';
interface Context {
state: State;
aaa: () => void;
}
interface State {
theme: string;
}
interface Action {
type: ActionType;
payload: string;
}
enum ActionType {
AAA = 'AAA',
}
const ThemeContext = React.createContext({
state: {
theme: 'linght',
},
aaa: (): void => {
alert('aaa');
},
});
function higherOrderComponent(Component: React.SFC<{ theme: Context }>) {
return (props: any): JSX.Element => {
return (
<ThemeContext.Consumer>
{theme => <Component {...props} theme={theme} />}
</ThemeContext.Consumer>
);
};
}
function Button(props: { theme: Context }): JSX.Element {
console.log(props);
const { state, aaa } = props.theme;
const handleClick = (): void => {
aaa();
};
return <button onClick={handleClick}>{state.theme}</button>;
}
const ThemeButton = higherOrderComponent(Button);
class ThemeButton2 extends React.Component<any, any> {
context = {} as Context;
static contextType = ThemeContext;
render(): JSX.Element {
return <Button theme={this.context} />;
}
}
class App extends React.Component<any, State> {
constructor(props: any) {
super(props);
this.state = {
theme: 'dark',
};
this.handleClick = this.handleClick.bind(this);
}
// Dispatcher
dispatch(action: Action): Action {
if (typeof action.type === 'undefined') {
throw new Error('Actions may not have an undefined "type" property.');
}
const nextState: State = this.reducer(this.state, action);
this.setState(() => ({
theme: nextState.theme,
}));
return action;
}
// Reducer
reducer(state: State, action: Action): State {
switch (action.type) {
case ActionType.AAA:
return {
...state,
theme: action.payload,
};
default:
return state;
}
}
// ActionCreator
aaa(): Action {
// Action
return {
type: ActionType.AAA,
payload: 'aaa',
};
}
handleClick(): void {
this.dispatch(this.aaa());
}
render(): JSX.Element {
const Fragment = React.Fragment;
return (
<Fragment>
{/** this.state.theme is used as value */}
<ThemeContext.Provider
value={{
state: this.state,
aaa: this.handleClick,
}}
>
<ThemeButton />
</ThemeContext.Provider>
{/** Default Value is used as value */}
<ThemeButton />
{/** ContextType is used as value */}
<ThemeButton2 />
<p>theme: {this.state.theme}</p>
</Fragment>
);
}
}
export default App;