创建三个组件

  • Father 父组件
  • Son 子组件
  • Gson 孙组件
// Father
import React, {useState} from 'react';
import Son from 'views/Son/index.jsx'
import context from 'utils/context'

export default function Father () {
const [count, setCount] = useState(10000)

const handleCount = (count) => {
setCount(count)
}

const data = {
count,
handleCount
}

return (
<context.Provider value={data}>
Father组件, {count}
<hr/>
<Son></Son>
</context.Provider>
)
}
// Son

import React, { useContext } from 'react';

import Gson from 'views/Gson/index.jsx'
import context from 'utils/context'

export default function Son() {
const data = useContext(context)
console.log(data);

return (
<div>
Son 组件, {data?.count}
<hr/>
<Gson></Gson>
</div>
)
}
// Gson

import React, { useContext } from 'react';

import context from 'utils/context'

export default function Gson () {

const {count, handleCount} = useContext(context)

const handleReduce = () => {
if(count <= 10000){
return
}
handleCount(count - 5)
}

const handleAdd = () => {
handleCount(count + 5 )
}

return (
<div>
Gson 组件, {count}
<div>
<button onClick={handleReduce}>-5</button>
&nbsp;&nbsp;&nbsp;&nbsp;
<button onClick={handleAdd}>+5</button>
</div>
</div>
)
}

效果

  • 点击孙组件,实现数据响应,更新视图
    1
  • react中使用context数据通信 useContext_数据

  • 2
  • react中使用context数据通信 useContext_数据_02