- 公告信息(语言、主题)如何传递给每个组件
- 用 props 太繁琐
- 用 redux 小题大做
import React from 'react';
// 创建 Context 填入默认值(任何一个 js 变量)
const ThemeContext = React.createContext('light');
/* class 组件 */
class ThemeButton extends React.component {
...
render() {
const theme = this.context; // React 会往上找最近的 theme Provider
return <p>theme is {theme}</p>
}
// static contextType = ThemeContext 或者
}
ThemeButton.contextType = ThemeContext;
/* 函数组件 */
function ThemeLink () {
// const theme = this.context; 会报错 函数组件没有实例
return
<ThemeContext.Consumer>
{ value => <p>theme is {value}</p> }
</ThemeContext.Consumer>
}
function Toolbar() {
return (
<div>
<ThemeButton />
<ThemeLink />
</div>
)
}
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
theme: 'light'
}
}
render() {
return
<ThemeContext.Provider value={this.state.theme}>
<Toolbar />
<hr />
<button onClick={this.changeTheme}>change theme</button>
</ThemeContext.Provider>
}
changeTheme = () => {
this.setState({
theme: this.state.theme === 'light' ? 'dark' : 'light'
})
}
}