首页 > 解决方案 > 如何为特定页面创建父组件(以便能够在父级中添加反应上下文)?

问题描述

如何创建将包裹这些特定页面的父组件(包装器),然后在该父组件中添加上下文?

标签: reactjsnext.jsreact-context

解决方案


您可以使用 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);

推荐阅读