Context实现跨组件通信

/** @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;

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值