【发布时间】:2020-10-16 08:54:51
【问题描述】:
简而言之,我在项目的根目录中获得了一个全局上下文——它被提供给子组件。其中一个子组件本身需要是上下文提供者,但它的子组件需要访问这两个上下文。
虽然我可以将字段附加到第一个上下文(例如解构上下文并向子对象添加更多内容),但我不知道如何。
然后我创建了另一个上下文(子上下文)并包装了子上下文,但是当我访问它时,只有子上下文可用,而不是全局上下文。
示例。
// DrawerContext Context component
import React, { createContext } from 'react'
const DrawerContext = createContext()
export default DrawerContext
// GlobalContext Context component
import React, { createContext } from 'react'
const GlobalContext = createContext()
export default GlobalContext
---
// So root has ..
<GlobalContext.Provider value={{
someValue: someValue }}>
<Child />
</GlobalContext.Provider>
// Child has ...
<DrawerContext.Provider value={{
anotherValue: anotherValue
}}>
<subChild />
</DrawerContext.Provider>
// Subchild ...
const drawerContext = useContext(DrawerContext) // This has values
const context = useContext(GlobalContext) // This is undefined .. :(
【问题讨论】:
标签: reactjs react-context