You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

44 lines
998 B

import React, { createContext, useContext, useState } from 'react'
// 1.创建 Context 对象,调用 createContext 方法
const Context = createContext()
function ComA() {
const count = useContext(Context)
return (
<div>
this is ComA
<br />
传过来的数据为{count}
<ComC />
</div>
)
}
function ComC() {
// 3.底层组件通过 useContext 函数获取数据
const count = useContext(Context)
return (
<div>
this is ComC
<br />
传过来的数据为{count}
</div>
)
}
function App() {
const [ count, setCount ] = useState(0)
return (
// 2.顶层组件通过 Context.Provider 提供数据
<Context.Provider value={count}>
<div>
<ComA />
<button onClick={() => {setCount(count + 1)}}>+</button>
</div>
</Context.Provider>
)
}
export default App