【问题标题】:How to access the context of a unknown parent如何访问未知父级的上下文
【发布时间】:2020-09-17 16:40:40
【问题描述】:

假设,我有两个独立的组件 X 和 Y,其中 X 是 Y 中的依赖项(不是项目中的直接子项)。是否可以在 X 中访问 Y 的上下文?

例如:

<Y.Provider value={key: 'val'}>
   <X />
</Y.Provider>

X是一个单独的项目想访问Y的上下文,怎么办? 我可以在 X 中导入 Y 的上下文并使用它吗? Y 完全是一个单独的(直到 X 被用作 Y 中的依赖项才知道)组件?

【问题讨论】:

    标签: javascript reactjs react-native react-context use-context


    【解决方案1】:

    如果要访问某个父变量,则父变量必须将其作为道具传递。

    Y 可以将所需的道具传递给它的孩子

    const Y = (props) => {
       const myVariable = 1
    
       return React.cloneElement(props.children, { context: myVariable })
    }
    

    然后X可以通过props.context.myVariable访问它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-08
      • 2015-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-02
      • 2013-08-31
      • 1970-01-01
      相关资源
      最近更新 更多