title: React 进阶 date: 2020-05-09 11:43:23
tags: React
Context
- props 属性是由上到下单向传递的
- Context 提供了在组件中共享此类值的方法
案例:主题切换
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
| import React from "react";
const themes = { light: { classnames: "btn btn-primary", bgColor: "#eeeeee", color: "#000", }, dark: { classnames: "btn btn-light", bgColor: "#222222", color: "#fff", }, }; class App extends Component { constructor(props) { super(props); } render() { return ( <div calssName="App"> <header className="App-header"> <a href="#theme-switcher" className="btn btn-light"> 浅色主题 </a> <a href="#theme-switcher" className="btn btn-secondary"> 深色色主题 </a> </header> </div> ); } } export default App;
|
新建 Context 文件,Context 是 object,不是 component.在 src 下.
1 2 3 4 5 6
| import React from "react";
const ThemeContext = React.creatContext();
export default ThemeContext;
|
ThemeContext 返回两个值,一个是 Provider,一个是 Consumer.
ThemeContext.Provider 包裹根组件
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
| import React from 'react' import ThemeContext from '../theme-context'
const themes = { light: { classnames: 'btn btn-primary', bgColor: '#eeeeee', color: '#000' }, dark: { classnames: 'btn btn-light', bgColor: '#222222', color: '#fff' } } class App extends Component { constructor(props){ super(props) this.state = { theme: 'light' } this.changeTheme = this.changeTheme.bind(this) } change(theme){ this.setState({ theme }) } render(){ return ( <ThemeContext.Provider value={themes.light}> <div calssName="App"> <header className="App-header"> <a href="#theme-switcher" className="btn btn-light" onClick={() => {this.changeTheme('light')}} >浅色主题</a> <a href="#theme-switcher" className="btn btn-secondary" onClick={() => {this.changeTheme('dark')} >深色色主题</a> </header> </div> </ThemeContext.Provider> ) } } export default App
|
新建组件 themeBar.js 组件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| import React from "react"; import ThemeContext from "../theme-context";
const ThemeBar = () => { return ( <themeContext.Consumer> {(theme) => { return ( <div className="alert mt-5" style={{ backgroundColor: theme.bgColor, color: theme.color }} > 样式区域 <button className={theme.classname}>样式按钮</button> </div> ); }} </themeContext.Consumer> ); }; export default ThemeBar;
|