In React, how do I detect if my component is rendering from the client or the server?

前端 未结 9 1300
夕颜
夕颜 2020-12-29 18:41

I\'m building a isomorphic application, but I\'m using a third-party component that only renders on the client. So, particularly for this component, I need to only render it

9条回答
  •  遥遥无期
    2020-12-29 19:41

    At the topmost level of the server Element hierarchy, one could add a ServerContext such as this:

    class ServerContext extends React.Component {
      getChildContext() { return { isServer: true }; }
      render() { return React.Children.only(this.props.children); }
    }
    
    ServerContext.propTypes = {
      children: React.PropTypes.node.isRequired,
    };
    
    ServerContext.childContextTypes = {
      isServer: React.PropTypes.bool.isRequired,
    };
    
    // Create our React application element.
    const reactAppElement = (
      
        
          
            
          
        
      
    );
    

    Doing so, it should be possible to read the isServer from the context like this:

    const Layout = (_, { isServer }) => (
      // render stuff here
    );
    

提交回复
热议问题