gpt4 book ai didi

javascript - React.js 如何避免某些组件的服务端渲染?

转载 作者:行者123 更新时间:2023-11-29 17:56:19 25 4
gpt4 key购买 nike

我只想在服务器上渲染 React 以用于 SEO 目的,并且不需要在服务器上渲染某些组件。在这种情况下,如何忽略某些组件的服务器渲染?

最佳答案

我推荐一个使用 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));

关于javascript - React.js 如何避免某些组件的服务端渲染?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38745546/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com