我想在服务器上呈现React仅用于SEO目的,并且不需要在服务器上呈现某些组件。在这种情况下,如何忽略某些组件的服务器渲染?
答案 0 :(得分:4)
我建议使用React's context内的参数来控制渲染的高阶组件。这将允许您包装仅应在客户端上使用HoC进行渲染的组件,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));