reactjs - 如何为特定页面创建父组件(以便能够在父级中添加反应上下文)?
问题描述
- 我有一组特定的页面将使用特定的反应上下文。
- 我不想在 app.js 根文件中创建上下文,因为我只会在特定的页面集上使用该上下文。
如何创建将包裹这些特定页面的父组件(包装器),然后在该父组件中添加上下文?
解决方案
您可以使用 HOC 概念来解决此问题:
const Context = React.createContext({ ... });
const withPageContext = (PageComponent) => {
const Wrapper = (props) => {
return (
<Context.Provider value={...}>
<PageComponent {...props} />
</Context.Provider>
)
};
return hoistStatics(Wrapper, PageComponent, {
// `getInitialProps` not in hoist static list, so we add it here to prevent override
getInitialProps: true,
})
};
然后它可以pages/*
像这样用于你:
const MyPage = () => {
const ctx = useContext(Context);
};
export default withPageContext(MyPage);
推荐阅读
- c# - Powershell 脚本错误“找不到“LoadFromCollection”和参数计数的重载:“1”。”
- java - Java Web 客户端 CXF - JAXB 编组异常;嵌套异常是 javax.xml.bind.MarshalException
- c# - Scrollviewer 不会停在窗口边框
- laravel - 如何在 laravel 7 中创建路由组
- loops - Anylogic检测和迭代放置在另一个代理(主)上的代理
- c++ - 节点原生插件:在工作线程中将字符串参数转换为 UTF-8
- python - Python火柴游戏
- python - Opencv getPerspectiveTransform 方法给出的结果不清楚
- html - 为什么我添加的其中一张图片没有对齐?
- docker - 在一个阶段构建一个 docker 文件并在后续阶段使用它,而无需将其推送到 Gitlab 中的 docker hub