【发布时间】:2020-09-29 01:52:54
【问题描述】:
我有一个 CommonChild 组件,它调用了两个组件:Parent1 和 Parent2。
粗体Parent1 和Parent2 使用不同的AppContext。
请看下面的一些简单代码:
import React, { useState, useContext, createContext } from 'react'
//Create two createContext of Parents
const ContextParent1 = createContext();
const ContextParent2 = createContext();
//Create two providers of Parents
const AppProviderParent1 = (props) => {
const [state] = useState("This is AppProviderParent1")
return (
<ContextParent1.Provider value={state}>
{props.children}
</ContextParent1.Provider>
)
}
const AppProviderParent2 = (props) => {
const [state] = useState("This is AppProviderParent2")
return (
<ContextParent2.Provider value={state}>
{props.children}
</ContextParent2.Provider>
)
}
//Two parents called CommonChild, but different AppProvider (created above)
const Parent1 = (props) => {
return (
<AppProviderParent1 {...props}>
<CommonChild />
</AppProviderParent1>
)
}
const Parent2 = (props) => {
return (
<AppProviderParent2 {...props}>
<CommonChild />
</AppProviderParent2>
)
}
//CommonChild that try to use useContext to get value
const CommonChild = () => {
const context = useContext(...) //how to use useContext?
return (
<p>This is CommonChild Component</p>
)
}
我不知道如何在CommonChild 中合理地使用useContext。
感谢您的帮助
【问题讨论】:
-
您创建一个单独的上下文
const MyContext = createContext(<Default value here>);,然后在更改您提供的value属性的每个父母中为该上下文创建提供程序。然后通过调用const context = useContext(MyContext)使用子上下文中的上下文,如果没有找到父上下文,它将接收最相关的父上下文或默认值。 -
哦。你的意思是,
AppProviderParent1和AppProviderParent2都可以使用相同的createContext? -
是的,如果他们持有的属性没有区别的话。即父 1 可以提供值
{ propA: true},父 2 可以提供值{ propA: false} -
我会试试的。谢谢
-
这里是一个例子https://stackblitz.com/edit/react-ts-jheevm?file=index.tsx。注意:使用打字稿
标签: reactjs react-hooks use-context