react中createContext以及useContext的简单使用
1、在父组件中定义数据
在这里需要特别注意的是:定义createContext后需要导出,在其他页面必须要引入才可以使用
import React, { Suspense, createContext } from "react";
import { ContextA } from "./components/ContextA";
import { ContextB } from "./components/ContextB";
export const CountContext = createContext({
name: "杨幂",
age: 12,
sex: "女",
});
export const App = () => {
return (
<Suspense fallback={<div>数据正在加载中。。。</div>}>
<CountContext.Provider value={{ sex: "女", name: "杨幂", age: 12 }}>
<ContextA />
<ContextB />
</CountContext.Provider>
</Suspense>
);
};
2、子组件页面
import React, { useContext } from "react";
import { CountContext } from "../App";//将父组件中定义的进行导入
export const ContextA = () => {
const message = useContext(CountContext);
return (
<div>
{message?.name} - {message?.age} -{message?.sex}
</div>
);
};