• 公告信息(语言、主题)如何传递给每个组件
    • 用 props 太繁琐
    • 用 redux 小题大做
    1. import React from 'react';
    2. // 创建 Context 填入默认值(任何一个 js 变量)
    3. const ThemeContext = React.createContext('light');
    4. /* class 组件 */
    5. class ThemeButton extends React.component {
    6. ...
    7. render() {
    8. const theme = this.context; // React 会往上找最近的 theme Provider
    9. return <p>theme is {theme}</p>
    10. }
    11. // static contextType = ThemeContext 或者
    12. }
    13. ThemeButton.contextType = ThemeContext;
    14. /* 函数组件 */
    15. function ThemeLink () {
    16. // const theme = this.context; 会报错 函数组件没有实例
    17. return
    18. <ThemeContext.Consumer>
    19. { value => <p>theme is {value}</p> }
    20. </ThemeContext.Consumer>
    21. }
    22. function Toolbar() {
    23. return (
    24. <div>
    25. <ThemeButton />
    26. <ThemeLink />
    27. </div>
    28. )
    29. }
    30. class App extends React.Component {
    31. constructor(props) {
    32. super(props)
    33. this.state = {
    34. theme: 'light'
    35. }
    36. }
    37. render() {
    38. return
    39. <ThemeContext.Provider value={this.state.theme}>
    40. <Toolbar />
    41. <hr />
    42. <button onClick={this.changeTheme}>change theme</button>
    43. </ThemeContext.Provider>
    44. }
    45. changeTheme = () => {
    46. this.setState({
    47. theme: this.state.theme === 'light' ? 'dark' : 'light'
    48. })
    49. }
    50. }