react中hooks--useContext用法

useContext⽤于在快速在函数组件中导⼊上下⽂。

import React, { useContext } from "react";
const Context = React.createContext();
const Provider = Context.Provider;
export default function HookContext() {
 const store = {
 userName: "xiaoming",
 };
 return (
 <div>
 <h1>HookContext ⻚⾯</h1>
 <Provider value={store}>
 <Child />
 </Provider>
 </div>
 );
}
function Child(props) {
 const { userName } = useContext(Context);
 return (
 <div>
 Child
 <div>userName: {userName}</div>
 </div>
 );
}
posted @ 2022-03-03 08:42  Cupid05  阅读(73)  评论(0编辑  收藏  举报