Hooks 中使用 Context 全局数据
useContext 是必须要用的
父组件如同 class,也得使用 createContext,里面包裹层
import React, { useState, createContext } from 'react'
import SecondComponent from './Second'
export const CountContext = createContext()
function App(props) {
const [count, setcount] = useState(0)
return (
<div>
<div>{count}</div>
<button onClick={handleClick}>点击</button>
<CountContext.Provider value={count}>
<SecondComponent></SecondComponent>
</CountContext.Provider>
</div>
)
function handleClick() {
setcount(count + 1)
}
}
export default App
- 子组件不一样了,是用了 useContext
import React, { useContext } from 'react'
import { CountContext } from './App'
function SecondCompoent(props) {
const count = useContext(CountContext)
return <h1>{count}</h1>
}
export default SecondCompoent