父组件
import React, { useState} from "react"; import Counter from './Counter' import myContext from './createContext' function App() { const [count, setCount] = useState(0); return ( <div> <h4>我是父组件</h4> <p>点击了 {count} 次!</p> <button onClick={() => { setCount(count + 1); }} > 点我 </button> {/* 关键代码 */} {/* 提供器 */} <myContext.Provider value={count}> <Counter /> </myContext.Provider> </div> ); } export default App;
子组件
import React, { useContext} from 'react'; import myContext from './createContext' // 关键代码 function Counter() { const count = useContext(myContext); // 得到父组件传的值 return ( <div> <h4>我是子组件</h4> <p>这是父组件传过来的值:{count}</p> </div> ) } export default Counter;
效果: