React入门006之ContextApi03换肤功能

换肤功能

index.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
import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const themeContext = React.createContext();

function Button() {
return <button>button</button>;
}

function Input() {
return <input />;
}

function Box(props) {
return <div className={`box ${props.theme}`}>{props.children}</div>;
}

class App extends React.Component {
constructor() {
super();
this.state = {
theme: "light"
};
}
change() {
let res = this.state.theme === "green" ? "red" : "green";
this.setState({
theme: res
});
}
render() {
return (
<themeContext.Provider value={this.state.theme}>
<div className="App">
<button onClick={this.change.bind(this)}>换肤</button>
<themeContext.Consumer>
{theme => {
return (
<div>
<Box theme={theme}>
<Button />
</Box>
<Box theme={theme}>
<Input />
</Box>
</div>
);
}}
</themeContext.Consumer>
</div>
</themeContext.Provider>
);
}
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

style.css

1
2
3
4
5
6
7
8
9
10
11
12
.App {
font-family: sans-serif;
text-align: center;
}

.box.green {
border: 1px solid green;
}

.box.red {
border: 1px solid red;
}