1.父组件代码
import React, { useState } from 'react'; import Child from './child.js' import CountContext from './createContext' function Example(){ const [count , setCount ] = useState(0) return( <div> <div> <p>you click {count} times</p> <button onClick={()=>{setCount(count+1)}}>click me</button> <CountContext.Provider value ={count}> <Child/> </CountContext.Provider> </div> </div> ) } export default Example
2.子组件代码
import React, { useContext } from 'react'; import CountContext from './createContext' function Child(){ let count = useContext(CountContext) return(<h2>{count}</h2>) } export default Child
3.公共createContext.js文件代码
import {createContext } from 'react'; const CountContext = createContext(null); export default CountContext