/
app.js
97 lines (87 loc) · 2 KB
/
app.js
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
const themes = {
light: {
color: '#000',
background: '#eee',
},
dark: {
color: '#fff',
background: '#222',
},
};
// 创建 React context 赋默认值
const ThemeContext = React.createContext({
theme: themes.dark,
toggleTheme: () => {},
});
const UserContext = React.createContext({
name: 'jsonz',
});
// 用 Consumer的方式获取多个contextValue
const FunctionContext = () => (
<ThemeContext.Consumer>
{({theme: {color, background}, toggleTheme}) => {
return (
<UserContext.Consumer>
{user => (
<React.Fragment>
<button
onClick={toggleTheme}
style={{ color, background }}
>
{background}
</button>
<p>{user}</p>
</React.Fragment>
)}
</UserContext.Consumer>
);
}}
</ThemeContext.Consumer>
);
const FunctionWrap = () => (
<React.Fragment>
<FunctionContext />
</React.Fragment>
);
// 用class.contextType && this.context 的方式
class ClassContext extends React.Component {
static contextType = ThemeContext;
render() {
const {
theme: { color, background },
} = this.context;
return (
<React.Fragment>
<p style={{ color, background }}>{background}</p>
</React.Fragment>
);
}
}
const ClassWrap = () => (
<React.Fragment>
<ClassContext />
</React.Fragment>
);
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
theme: themes.light,
toggleTheme: () =>
this.setState(state => ({
theme: state.theme === themes.dark ? themes.light : themes.dark,
})),
};
}
render() {
return (
<ThemeContext.Provider value={this.state}>
<UserContext.Provider value={'jsonz1993'}>
<ClassWrap />
<FunctionWrap />
</UserContext.Provider>
</ThemeContext.Provider>
);
}
}
ReactDOM.render(<App/>, document.getElementById('container'));