Is it possible to pass context into a component instantiated with ReactDOM.render?

后端 未结 2 861
北恋
北恋 2020-12-06 02:46

TL;DR Given the following example code:

ReactDOM.render(, someDomNode);

Is it possible to manually pas

相关标签:
2条回答
  • 2020-12-06 02:47

    No. Before react 0.14 there was method React.withContext, but it was removed.

    However you can do it by creating HoC component with context, it would be something like:

    import React from 'react';
    
    function createContextProvider(context){
      class ContextProvider extends React.Component {
        getChildContext() {
          return context;
        }
    
        render() {
          return this.props.children;
        }
      }
    
      ContextProvider.childContextTypes = {};
      Object.keys(context).forEach(key => {
        ContextProvider.childContextTypes[key] = React.PropTypes.any.isRequired; 
      });
    
      return ContextProvider;
    }
    

    And use it as following:

    const ContextProvider = createContextProvider(context);
    
    ReactDOM.render(
      <ContextProvider>
        <MyComponent prop1={someVar} />
      </ContextProvider>,
      someDomNode
    );
    
    0 讨论(0)
  • 2020-12-06 02:53

    In React 15 and earlier you can use ReactDOM.unstable_renderSubtreeIntoContainer instead of ReactDOM.render. The first argument is the component who's context you want to propagate (generally this)

    In React 16 and later there's the "Portal" API: https://reactjs.org/docs/portals.html

    0 讨论(0)
提交回复
热议问题