context作用:用于爷孙组件通信,孙子可以直接修改数据,爷爷组件数据也响应被改动。
1、新建context.js存放内容和定义修改方法,mall.js是父组件引入封装的context包裹子组件,mallson.js子组件可以获取调用传入的数据和方法。
’2、创建context.js进行封装,数据也在此处定义,这里创建名为MyContext 的context,后续子组件使用的时候名字要相同才能找到这个
import React, { createContext, useState, useContext } from "react";
// 子组件需要引入MyContext才能使用
const MyContext = createContext();
//封装引入语句
const useCreateContext = () => {
return useContext(MyContext);
};
// 最上一层的父组件需要用MyProviderContext,children就是内部的node节点,直接渲染
export const MyProviderContext = ({children}) => {
const [mallData, setMallData] = useState(1);
const changeMallData = () => {
setMallData((s) =>{
console.log(s)
return s+1
// s + 1
});
};
const initialState = {
data: mallData,
setData: changeMallData,
};
return (
{/* initialState 为子组件提供的数值 */}
<MyContext.Provider value={initialState}>
{children}
</MyContext.Provider>
);
};
export { MyContext, useCreateContext };
3、mall.js引入context,爷/父组件用MyProviderContext包裹需要传递的组件,这样被包裹的组件就能获取封装的数据。
import React, { useContext } from "react";
import { MyProviderContext } from "../../components/context/context";
import Mallson from "./mellson";
const Mall = () => {
return (
<div>
********** Mall组件内*************
<MyProviderContext>
<Mallson></Mallson>
</MyProviderContext>
</div>
);
};
3、mallson.js使用context数据,孙/子组件可以直接修改内容。其他页面使用到的数据也会被修改
import React, { useContext, useState } from "react";
import { MyContext ,useCreateContext} from "../../components/context/context";
const Mallson = () => {
//使用useContext,MyContext名字要相同
const { data, setData } = useCreateContext()//useContext(MyContext);
return (
<>
<p>-------Mallson组件分割线-------</p>
<div
className="mall-son"
style={{ width: 300, backgroundColor: "#e0e9ff", height: 100 }}
>
子代获取context:{data}
<button onClick={setData}>修改context</button>
</div>
</>
);
};
export default Mallson;