Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

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

TL;DR Given the following example code:

ReactDOM.render(<MyComponent prop1={someVar} />, someDomNode);

Is it possible to manually pass React context into the instance of MyComponent?

I know this sounds like a weird question given React's nature, but the use case is that I'm mixing React with Semantic UI (SUI) and this specific case is lazy-loading the contents of a SUI tooltip (the contents of the tooltip is a React component using the same code pattern as above) when the tooltip first displays. So it's not a React component being implicitly created by another React component, which seems to break context chain.

I'm wondering if I can manually keep the context chain going rather than having components that need to look for certain data in context AND props.

React version: 0.14.8

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...