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