createContext 的使用
- 使用场景:跨组件共享数据
- Context 作用:实现跨组件传递数据,而不必在每一个组件传递props ,简化组件之间数据传递的过程
<Context.Provider value>
:通过 value 属性提供数据。‘<Context.Consumer>
:在 JSX 中获取 Context 中提供的数据。- 使用Provider 组件,如果传递了 value ,Consumer 获取到的是 Provider 中的 value 属性值
- 如果祖先组件没有使用 Provider ,那么 Consumer 获取到的是 createContext (defaultValue)的 defaultValue 值
代码
countContext.js
import { createContext } from 'react'
export const Context = createContext()
App.js
import React from 'react'
import { Context } from './countContext'
import Parent from './Parent'
export default function App() {
return (
<Context.Provider value={{ count: 0 }}>
App
<hr />
<Parent />
</Context.Provider>
)
}
Parent.js
import Child from './Child'
export default function Parent() {
return (
<div>
Parent
<hr />
<Child />
</div>
)
}
Child.js
import { context } from './countContext'
export default function Child() {
return (
<Context.Consumer>
{(value) => {
return (
<div>
Child
<h3>{value.count}</h3>
</div>
)
}}
</Context.Consumer>
)
}
useContext 使用
- 作用:在函数组件中,获取Context.Provider 提供的数据
- 参数:Context 对象,即通过 createContext 函数创建的对象
- 返回值:Context.Provider 提供的 value 数据
import { useContext } from 'react' import { Context } from './countContext' export default function Child() { const value = useContext(Context) return ( <div> Child <h3>{value.count}</h3> </div> ) }