在 React JS 中使用多个上下文

Using multiple contexts in React JS

我是 React JS 的新手,我正在努力使上下文的使用正常工作。

我有一个应用程序,当入口组件(App)定义为

    <Router>
        <div className="app">
            <GlobalContextProvider>
                <Header />
                <Switch>
                    <Route path="/CodeSystem" component={PageCodeSystem} />
                    <Route path="/ValueSet" component={PageValueSet} />
                    <Route path="/RefSets" component={PageRefSets} />
                    <Route path="/" exact component={HomePage} />
                </Switch>
            </GlobalContextProvider>
        </div>
    </Router>

在组件树的下方,我有一个组件,它使用自己的与其子组件共享的上下文。

        <QueryVSContextProvider>
            <ValueSetSidebar />
            <ValueSetBody />
        </QueryVSContextProvider>

从上面,在 ValueSetBody 组件中我有:

class ValueSetBody extends Component {
    static contextType = QueryVSContext;

    render() {
        const { bundle } = this.context;

        ...

        }
}

我怎样才能访问在 App 组件中定义的“GlobalContext”? 我希望能够从 class 组件检测到 GlobalContext 的变化。

谢谢

最简单的方法是使用 <Context.Consumer>。例如:

class ValueSetBody extends Component {

    ...

    render() {
        <QueryVSContext.Consumer>
            {queryVSContext =>
                (<GlobalContext.Consumer>
                    {globalContext =>
                        (<div>
                            {queryVSContext.value}
                            {globalContext.value}
                            ...
                        </div>)
                    }
                </GlobalContext.Consumer>)
            }
        </QueryVSContext.Consumer>
    }
}

如果您要在很多地方使用上下文,那么创建 HOC 或使用 render-prop 技术可能会更好。 HOC 示例:

function connectGlobalContext(Component) {
    return function (props) {
        return <GlobalContext.Consumer>
            {context =>
                <Component {...props} globalContext={context}/>
            }
        </GlobalContext.Consumer>
    }
}

创建 HOC 后,您可以包装需要上下文的组件:

class ValueSetBody extends Component {
    ...
    render() {
        return (<div>
            {this.props.globalContext.value}
        </div>)
    }
}

export default connectGlobalContext(ValueSetBody);

现在您可以以相同的方式为 QueryVSContext 创建 HOC,并在任何需要的地方使用这两种上下文。