context是什么

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

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

context使用

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

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

context用法

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

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

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

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

3.创建ThemeBar组件

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

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

版权声明:本文为dropInInt原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/dropInInt/p/11996769.html