爷爷组件
export default function App() {
const [flag, setFalg] = useState(false);
const handelFlag = () => {
setFalg(!flag)
}
<div>
<Context.Provider value={{ flag: flag,changeFlag:handelFlag }}>
<Father/>
</Context.Provider>
父组件
import React,{useContext} from 'react'
import BigCircle from './BigCircle'
import Btn from './Btn';
import {Context}from '../App'
export default function Father() {
return (
<div>
<Btn />
<BigCircle />
</div 子组件
import React,{useContext} from 'react'
import {Context}from '../App'
export default function BigCircle() {
const {flag}=useContext(Context);
return (
<div style={{width:'100px',height:'100px',background:flag?'red':'green'}}>
</div>
)
}
子组件
import React,{useContext} from 'react'
import {Context}from '../App'
export default function Btn() {
const {changeFlag } = useContext(Context);
return (
<div>
<button onClick={changeFlag}>点击</button>
</div>
)
}
参考链接 React Hook之useContext的介绍与使用_四川省奇呱科技有限公司-CSDN博客_usecontext