You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

43 lines
998 B

2 years ago
  1. import React, { createContext, useContext, useState } from 'react'
  2. // 1.创建 Context 对象,调用 createContext 方法
  3. const Context = createContext()
  4. function ComA() {
  5. const count = useContext(Context)
  6. return (
  7. <div>
  8. this is ComA
  9. <br />
  10. 传过来的数据为{count}
  11. <ComC />
  12. </div>
  13. )
  14. }
  15. function ComC() {
  16. // 3.底层组件通过 useContext 函数获取数据
  17. const count = useContext(Context)
  18. return (
  19. <div>
  20. this is ComC
  21. <br />
  22. 传过来的数据为{count}
  23. </div>
  24. )
  25. }
  26. function App() {
  27. const [ count, setCount ] = useState(0)
  28. return (
  29. // 2.顶层组件通过 Context.Provider 提供数据
  30. <Context.Provider value={count}>
  31. <div>
  32. <ComA />
  33. <button onClick={() => {setCount(count + 1)}}>+</button>
  34. </div>
  35. </Context.Provider>
  36. )
  37. }
  38. export default App