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.

42 lines
928 B

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