useContext及使用场景

1.使用 createContext 创建一个 Context对象,创建一个“上下文”
2.使用 Provider 提供值 value
3.使用 useContext 访问createContext 返回的 Context对象

import React, { useContext, createContext } from 'react';
// 创建一个 Context 对象
const MyContext = createContext();

function App() {
// 使用 Provider 包裹子组件,并提供 "newValue" 作为 context 值, 在组件树中用 Provider 包裹住它的子组件,以提供 context 的当前值给这些子组件。
const [user, setUser] = useState('');
return (
<MyContext.Provider value={{user, setUser}}>

</MyContext.Provider>
);
}

function Toolbar() {
return (




);
}

function MyComponent() {
// 在子组件内使用 useContext 获取 context 的值;你必须将 createContext() 时返回的对象作为参数传递给 useContext
const contextValue = useContext(MyContext);

return (


Context Value: {contextValue}

);
}

export default App;

参考文献 https://blog.csdn.net/qq_40868156/article/details/134560085

posted @ 2024-05-09 16:55  小白张先生  阅读(234)  评论(0)    收藏  举报