react中使用context数据通信 useContext
原创
©著作权归作者所有:来自51CTO博客作者wx58f59a601fad5的原创作品,请联系作者获取转载授权,否则将追究法律责任
创建三个组件
- 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>
<button onClick={handleAdd}>+5</button>
</div>
</div>
)
}
效果
- 点击孙组件,实现数据响应,更新视图
1 
- 2
