react之context

context是什么

Props属性是由上到下单向传递的

context提供了在组件中共享此类值的方法

context使用

设计目的是共享哪些对于组件来说全局的数据

不要因为仅仅为了避免在几个层级下的组件传递props而使用context

context用法

1.先创建一个theme-context.js

1 import React from 'react'
2 
3 const ThemeContext = React.createContext()
4 
5 export default ThemeContext

2.在组件app.js里面引用

 1 import React, { Component } from 'react';
 2 import './App.css';
 3 import ThemeContext from './theme-context'
 4 import ThemeBar from './components/ThemeBar'
 5 const themes = {
 6     light: {
 7         className: 'btn btn-prime',
 8         bgColor: '#f00',
 9         color: '#fff'
10     },
11     dark: {
12         className: 'btn btn-dark',
13         bgColor: '#ff0',
14         color: '#000'
15     }
16 }
17 
18 class App extends Component {
19     render() {
20         return (
21             <ThemeContext.Provider value={themes.light}>
22             <div>
23                 <ThemeBar/>
24             </div>
25             </ThemeContext.Provider>
26         );
27     }
28 }
29 
30 export default App;

3.创建ThemeBar组件

 1 import React from 'react'
 2 import ThemeContext from '../theme-context'
 3 
 4 const ThemeBar = () => {
 5     return (
 6         <ThemeContext.Consumer>
 7         {
 8             theme => {
 9                 console.log(theme)
10             }
11         }
12         </ThemeContext.Consumer>
13     )
14 }
15 
16 export default ThemeBar

在组件里面打印传递下来的theme就可以在控制台看见传递下来的数据了

原文地址:https://www.cnblogs.com/dropInInt/p/11996769.html