父组件
import React,{FC,createContext, useContext,useState} from "react"; import Counter from "./components"; export const MyContext = createContext(0); const Test:FC = () => { const [count,setCount] = useState(0) return ( <> <div>数值是:{count}</div> <button onClick={()=>{setCount(count+1)}}>我是按钮</button> <MyContext.Provider value={count}> <Counter /> </MyContext.Provider> </> ) } export default Test父组件
子组件
import React,{FC,createContext, useContext,useState} from "react"; import {MyContext} from '../index'; const Counter:FC = () => { const count = useContext(MyContext) return ( <> <div>这是{count}</div> </> ) } export default Counter子组件