【发布时间】:2019-12-21 19:39:21
【问题描述】:
这是codesandbox。
我可以通过子组件成功获取和设置上下文数据。但是为什么我不能在父级中访问它们?
const App: React.FC = () => {
const context = useContext(MyContext)
return (
<div className="App">
<MyContextProvider>
<Comp1 />
<Comp2 />
<p>
Result inside: {context.selection}
</p>
</MyContextProvider>
<p>
Result outside: {context.selection}
</p>
</div>
);
}
这是子组件。
const Comp1 = () => {
const context = useContext(MyContext)
return (
<div>
<p>current: {context.selection}</p>
<button onClick={() => context.setSelection && context.setSelection(123)}>Set to '123'</button>
</div>
)
}
这是上下文文件。
interface MyContextProviderType {
children: JSX.Element | JSX.Element[]
}
interface ContextProps {
selection: string
setSelection: Function
}
export const MyContext = createContext<Partial<ContextProps>>({})
export const MyContextProvider = ({children}: MyContextProviderType) => {
const [selection, setSelection] = useState('')
return (
<MyContext.Provider value={{selection, setSelection}}>
{children}
</MyContext.Provider>
)
}
感谢您的帮助!
【问题讨论】:
-
你不能;要使用上下文,您必须在提供者中。
-
这就是为什么我有内外尝试。
-
你有不能在
<MyContextProvider>中内外都包裹的用例吗?
标签: reactjs typescript react-hooks react-context