2016-08-03 6 views

답변

4

React's context 내의 매개 변수를 사용하여 렌더링을 제어하는 ​​Higher-order Component를 권하고 싶습니다. 이렇게하면 래핑 된 구성 요소를 렌더링할지 또는 서버에 배치할지 여부를 결정할 수있는 HoC를 사용하여 클라이언트에서만 렌더링해야하는 구성 요소를 래핑 할 수 있습니다.

var React = require('react'); 
var ReactDOMServer = require('react-dom/server'); 

// Should be added as a static contextTypes property on any component 
// needing access to the parameter. In this case, it's only the HoC 
var serverContextTypes = { 
    isServer: React.PropTypes.bool 
}; 

// Should be the root component of your server-side render to inject 
// the parameter into context 
var ServerContext = React.createClass({ 
    getChildContext: function() { 
     return { 
      isServer: true 
     }; 
    }, 

    render: function() { 
     // Only allows a single child 
     return React.Children.only(this.props.children); 
    } 
}); 

// Tells React which context types to pass to ServerContext's children 
ServerContext.childContextTypes = serverContextTypes; 

ServerContext.propTypes = { 
    children: React.PropTypes.element.isRequired 
}; 

// The HoC that determines if the wrapped component should be rendered 
var ClientOnly = function (Wrapped) { 
    var Component = React.createClass({ 
     render: function() { 
      if (this.context.isServer) { 
       return null; 
      } else { 
       return React.createElement(Wrapped, this.props); 
      } 
     } 
    }); 

    Component.contextTypes = serverContextTypes; 

    return Component; 
}; 

// Example React.Component that will always render 
var Content = React.createClass({ 
    render: function() { 
     return React.createElement('main', null, 'Important content that should always render'); 
    } 
}); 

// Example React.Component that will be omitted from server-side rendering 
var Extra = ClientOnly(React.createClass({ 
    render: function() { 
     return React.createElement('aside', null, 'Content to exclude in a React.Component'); 
    } 
})); 

// Example SFC that will be omitted from server-side rendering 
var ExtraSFC = ClientOnly(function() { 
    return React.createElement('aside', null, 'Content to exclude in a Stateless Functional Component'); 
}); 

// The App! 
var App = React.createClass({ 
    render: function() { 
     return React.createElement('div', {className: 'app'}, [ 
      React.createElement(Extra), 
      React.createElement(Content), 
      React.createElement(ExtraSFC) 
     ]); 
    } 
}); 

var element = React.createElement(ServerContext, null, 
    React.createElement(App) 
); 

console.log(ReactDOMServer.renderToString(element)); 
+0

네, 정상 작동합니다. 감사! – asiniy

관련 문제