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;