useContext的使用

1. 基本使用

父级组件
import React, { useState } from "react";
import Child from "./components/Child";

const parentValue = {
  num: 0
}
export const parentContext = React.createContext(parentValue);
const Ceshi = () => {
  const [parentState, setParentState] = useState(parentValue);
  const add = () => {
    setParentState(state => {
      return {
        ...state,
        num: state.num + 1
      }
    })
  }
  return <>
    <p>我是父级组件,当前数值:{parentState.num}</p>
    <button onClick={ add }>点击加1</button>
    <parentContext.Provider value={ parentState }>
      <Child></Child>
    </parentContext.Provider>
  </>
}
export default Ceshi;
子组件
import { useContext } from "react";
import { parentContext } from "../..";
const Child = () => {
  const stateContext = useContext(parentContext);
  return <>
    <p>我是子级组件,接收到的值为{stateContext.num}</p>
  </>
}
export default Child;

2.封装使用

公共组件
import React, { useState } from "react"
const defaultValue = {
  num: 0
}
export const stateContext = React.createContext(defaultValue);
export const stateContextFunc = React.createContext<React.Dispatch<React.SetStateAction<{
  num: number;
}>> | undefined>(undefined);

export const CeshiElem: React.FC = (props) => {
  const [ cs, setCs ] = useState(defaultValue);
  return <stateContext.Provider value={ cs }>
    <stateContextFunc.Provider value={ setCs }>
      { props.children }
    </stateContextFunc.Provider>
  </stateContext.Provider>
}
子组件使用
import { CeshiElem } from './ceshiContext'
<CeshiElem>
  <Ceshi/>
</CeshiElem>
Ceshi组件
import { useContext } from "react";
import Child from "./components/Child";
import { stateContext, stateContextFunc } from '../../ceshiContext';

const Ceshi = () => {
  const csValue = useContext(stateContext);
  const csFunc = useContext(stateContextFunc);
  const add = () => {
    csFunc!(state => {
      return {
        ...state,
        num: state.num + 1
      }
    });
  }
  return <>
    <p>我是父级组件,当前数值:{csValue.num}</p>
    <button onClick={ add }>点击加1</button>
    <Child/>
  </>
}
export default Ceshi;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Agwenbi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值