4个文件:
1.Xxxtext.tsx
2.Main.tsx
3.Child.tsx
4.GrandChild.tsx
3个api:
1.useContext
2.useReducer
3.createContext
1.Context.tsx
//1.Context.tsx
import { createContext } from "react";
interface IContext {
number: number;
dispatchNumbner: any;
}
// const Context = createContext(null); // 这样写会报错
export const Context = createContext<IContext>({
number: 0,
dispatchNumbner: null,
}); // 这样写不会报错
2.Main.tsx
//2.Main.tsx
import { useReducer } from "react";
import Child from "./Child";
import { Context } from "./Context";
const App = () => {
const [number, dispatchNumbner] = useReducer((state: any, action: any) => {
const { payload, name } = action;
switch (name) {
case "a":
return state + 1;
case "b":
return state - 1;
case "c":
return payload;
}
return state;
}, 0);
return (
<div>
<button onClick={() => dispatchNumbner({ name: "a" })}>增加</button>
<button onClick={() => dispatchNumbner({ name: "b" })}>减少</button>
<button onClick={() => dispatchNumbner({ name: "c", payload: 666 })}>
赋值
</button>
<div>{number}</div>
<Context.Provider value={{ number, dispatchNumbner }}>
<Child />
<br />
{/* <Child2 /> */}
</Context.Provider>
</div>
);
};
export default App;
3.Child.tsx
//3.Child.tsx
import { useContext } from "react";
import GrandChild from "./GrandChild";
import { Context } from "./Context";
const Child = () => {
const { number, dispatchNumbner } = useContext(Context);
// console.log(number);
return (
<div>
<h1>child</h1>
{number}
<br />
<button onClick={() => dispatchNumbner({ name: "b" })}>减少</button>
<br />
<GrandChild />
</div>
);
};
export default Child;
4.GrandChild.tsx
//4.GrandChild.tsx
import { useContext } from "react";
import { Context } from "./Context";
const Child = () => {
const { number, dispatchNumbner } = useContext(Context);
// console.log(number);
return (
<div>
<h1> child2</h1>
{number}
<br />
<button onClick={() => dispatchNumbner({ name: "b" })}>减少</button>
</div>
);
};
export default Child;