1. 全局上下文
    2. //CountContext/index.jsx
    3. import { createContext } from "react";
    4. export const CountContext=createContext()
    1. 爷爷组件/mine.jsx
    2. import React,{useState}from 'react'
    3. import {CountContext}from "../CountContext"
    4. import MineItem from '../MineItem'
    5. export default ()=>{
    6. const [count,setCount]=useState(0)
    7. return(
    8. <>
    9. <h1> 我是一个爷爷组件{count}</h1>
    10. <button onClick={()=>setCount(count+1)}>点击加一</button>
    11. <CountContext.Provider value={count}>
    12. <MineItem />
    13. </CountContext.Provider>
    14. </>
    15. )
    16. }
    1. //父组件/MineItem.jsx
    2. import React,{useContext}from 'react'
    3. import {CountContext}from "../CountContext"
    4. import MineItemSon from '../MineItemSon'
    5. // eslint-disable-next-line import/no-anonymous-default-export
    6. export default ()=>{
    7. let count=useContext(CountContext)
    8. return(
    9. <>
    10. <h2>我是一个子组件,传入的值为{count}</h2>
    11. <MineItemSon />
    12. </div>
    13. )
    14. }
    1. 孙子组件/MineItemSon.jsx
    2. import React,{useContext}from 'react'
    3. import {CountContext}from "../CountContext"
    4. export default ()=>{
    5. let count=useContext(CountContext)
    6. return(
    7. <>
    8. <h3> 我是一个孙子组件,传入的值为{count}</h3>
    9. </>
    10. )
    11. }