/** @format */
import React, { createContext, useContext, useState } from "react";
interface IGrandpa {
money: number;
setMoney: (money: number) => void;
car: number;
setCar: (car: number) => void;
}
const GrandpaContext = createContext<IGrandpa | undefined>(undefined);
const useGrandpaContext = () => {
const context = useContext(GrandpaContext);
if (!context) {
throw new Error("useMyContext must be used within a MyProvider");
}
return context;
};
const Grandpa = () => {
const [money, setMoney] = useState(100);
const [car, setCar] = useState(10);
return (
<GrandpaContext.Provider value={{ money, setMoney, car, setCar }}>
<div style={{ border: "1px red solid" }}>
这是grandpa组件
<p>money:{money}</p>
<button
onClick={() => {
setMoney(money - 1);
}}
>
使用money
</button>
<p>car:{car}</p>
<button
onClick={() => {
setCar(car - 1);
}}
>
使用car
</button>
<Father></Father>
</div>
</GrandpaContext.Provider>
);
};
const Father = () => {
return (
<div style={{ border: "1px red solid" }}>
这是father组件
<Son></Son>
</div>
);
};
const Son = () => {
// 方法1:
// const { money, setMoney, car, setCar } = useGrandpaContext();
// 方法2:
//可以使用非空断言(!)来告诉 TypeScript 它不会是 undefined
const { money, setMoney, car, setCar } = useContext(GrandpaContext)!;
return (
<div style={{ border: "1px red solid" }}>
这是Son组件
<p>money:{money}</p>
<button
onClick={() => {
setMoney(money - 1);
}}
>
使用money
</button>
<p>car:{car}</p>
<button
onClick={() => {
setCar(car - 1);
}}
>
使用car
</button>
</div>
);
};
function App() {
return <Grandpa></Grandpa>;
}
export default App;
Context实现跨组件通信
最新推荐文章于 2024-09-07 13:38:28 发布