我正在为 React SSR 应用程序使用这个非常棒的样板,并尝试为 css lib 添加Material UI。我已经阅读了他们的服务器端渲染指南,但似乎做错了什么,因为我可以让按钮按此处所示进行渲染,但是按钮没有应用样式:((
这是我到目前为止所做的:在 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>
我不确定我做错了什么?