我正在将这个非常出色的boilerplate用于React SSR应用程序,并试图为CSS lib添加Material UI。我已经阅读了他们的服务器端渲染指南,但似乎做错了,因为我可以按here所示来渲染按钮,但是没有对按钮应用样式:((
这是我到目前为止所做的: 在client.js中
// added for Material UI
import CssBaseline from '@material-ui/core/CssBaseline';
import { ThemeProvider } from '@material-ui/core/styles';
import theme from './theme/sitetheme';
...
const render = (Routes: Array) => {
const renderMethod = module.hot ? ReactDOM.render : ReactDOM.hydrate;
React.useEffect(() => {
const jssStyles = document.getElementById('#jss-server-side');
if (jssStyles) {
jssStyles.parentElement.removeChild(jssStyles);
}
}, []),
renderMethod(
<ThemeProvider theme={theme}>
<CssBaseline />
<AppContainer>
<Provider store={store}>
<ConnectedRouter history={history}>
{renderRoutes(Routes)}
</ConnectedRouter>
</Provider>
</AppContainer>
</ThemeProvider>,
// $FlowFixMe: isn't an issue
document.getElementById('react-view')
);
};
然后在server.js中
// added for Material UI
import CssBaseline from '@material-ui/core/CssBaseline';
import { ServerStyleSheets, ThemeProvider } from '@material-ui/core/styles';
import theme from './theme/sitetheme';
...
const extractor = new ChunkExtractor({ statsFile });
const sheets = new ServerStyleSheets(); // added for material-ui
const staticContext = {};
const AppComponent = (
sheets.collect(
{/* Setup React-Router server-side rendering */}
{renderRoutes(routes)}
));
const css = sheets.toString(); // for material ui
const initialState = store.getState();
const htmlContent = renderToString(AppComponent);
// head must be placed after "renderToString"
// see: https://github.com/nfl/react-helmet#server-usage
const head = Helmet.renderStatic();
// Check if the render result contains a redirect, if so we need to set
// the specific status and redirect header and end the response
if (staticContext.url) {
res.status(301).setHeader('Location', staticContext.url);
res.end();
return;
}
// Check page status
const status = staticContext.status === '404' ? 404 : 200;
// Pass the route and initial state into html template
res
.status(status)
.send(renderHtml(head, extractor, htmlContent, initialState, css));
最后是renderHtml.js
export default (
head: Object,
extractor: Function,
htmlContent: string,
initialState: Object,
css: string // added for Material UI
...
${extractor.getLinkTags()}
${extractor.getStyleTags()}
<style id="jss-server-side">${css}</style>
我不确定自己在做什么错吗?