|
|
@@ -0,0 +1,50 @@
|
|
|
+import { useContext, useState, createContext } from "react";
|
|
|
+// import { createContext } from "react";
|
|
|
+const UserContext = createContext(null);
|
|
|
+const ThemeContext = createContext(null);
|
|
|
+
|
|
|
+// provider 组件
|
|
|
+function UseLearnContext() {
|
|
|
+ // 跨组件数据共享
|
|
|
+ // const value = useContext(SomeContext)
|
|
|
+ const [user, setUser] = useState({
|
|
|
+ name: "图图"
|
|
|
+ })
|
|
|
+ const [theme, setTheme] = useState('light')
|
|
|
+
|
|
|
+ return (
|
|
|
+ <div>
|
|
|
+ <h1>useContext</h1>
|
|
|
+ <ThemeContext.Provider value={{ theme, setTheme }}>
|
|
|
+ <UserContext.Provider value={{ user, setUser }}>
|
|
|
+ <Main></Main>
|
|
|
+ </UserContext.Provider>
|
|
|
+ </ThemeContext.Provider>
|
|
|
+ </div>
|
|
|
+ )
|
|
|
+}
|
|
|
+
|
|
|
+// 接受组件 Context
|
|
|
+function Main() {
|
|
|
+ const { user, setUser } = useContext(UserContext);
|
|
|
+ const { theme, setTheme } = useContext(ThemeContext);
|
|
|
+ function handleClick() {
|
|
|
+ setUser({
|
|
|
+ name: '小妹'
|
|
|
+ })
|
|
|
+ }
|
|
|
+
|
|
|
+ function handleChange() {
|
|
|
+ setTheme('dark')
|
|
|
+ }
|
|
|
+ return (
|
|
|
+ <div >
|
|
|
+ <h1>新组件:我的用户是{user.name}</h1>
|
|
|
+ <h2>当前主题是:{theme == 'light' ? '浅色' : '深色'}</h2>
|
|
|
+ <button onClick={handleClick}>修改</button>
|
|
|
+ <button onClick={handleChange}>修改主题</button>
|
|
|
+ </div>
|
|
|
+ )
|
|
|
+}
|
|
|
+
|
|
|
+export default UseLearnContext;
|