直接上代码:
import React, { useContext } from "react";
const defaultValue="동경"
const MyContext = React.createContext(defaultValue);
function Child() {
const context = useContext(MyContext);
return <h2>defaultValue 被覆盖: {context}</h2>;
}
function Child2() {
const context = useContext(MyContext);
return <h2>defaultValue: {context}</h2>;
}
function App(){
return (
<>
<MyContext.Provider value={ "Tokyo" }>
<Child /> {/* defaultValue 被覆盖: Tokyo*/}
</MyContext.Provider>
<Child2/>{/* defaultValue: 동경*/}
</>
)
}
export default App;