【发布时间】:2022-07-06 03:18:44
【问题描述】:
我有一个新的 nextjs 应用程序的问题,我已经配置了 Material UI
每次我刷新页面(硬)时,样式不再正确,我必须在每个文件中重做修改以找到我以前的样式...
我给你看我的 _app 和 _document 文件
提前感谢您的帮助
_app.js
import React from "react";
import { CacheProvider } from "@emotion/react";
import { CssBaseline } from "@mui/material";
import { ThemeProvider } from "@mui/styles";
import createEmotionCache from "../styles/createEmotionCache";
import theme from "../config/MUITheme";
const clientSideEmotionCache = createEmotionCache();
const MyApp = ({ Component, emotionCache = clientSideEmotionCache, pageProps }) => (
<CacheProvider value={emotionCache}>
<ThemeProvider theme={theme}>
<CssBaseline />
<Component {...pageProps} />
</ThemeProvider>
</CacheProvider>
);
export default MyApp;
_document.js
import * as React from "react";
import Document, { Html, Head, Main, NextScript } from "next/document";
import createEmotionServer from "@emotion/server/create-instance";
import createEmotionCache from "../styles/createEmotionCache";
export default class MyDocument extends Document {
render() {
return (
<Html lang="en">
<Head>
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
MyDocument.getInitialProps = async (ctx) => {
const originalRenderPage = ctx.renderPage;
const cache = createEmotionCache();
const { extractCriticalToChunks } = createEmotionServer(cache);
/* eslint-disable */
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) =>
function EnhanceApp(props) {
return <App emotionCache={cache} {...props} />;
},
});
/* eslint-enable */
const initialProps = await Document.getInitialProps(ctx);
const emotionStyles = extractCriticalToChunks(initialProps.html);
const emotionStyleTags = emotionStyles.styles.map((style) => (
<style
data-emotion={${style.key} ${style.ids.join(" ")}}
key={style.key}
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{ __html: style.css }}
/>
));
return {
...initialProps,
// Styles fragment is rendered after the app and page rendering finish.
styles: [...React.Children.toArray(initialProps.styles), ...emotionStyleTags],
};
};
刷新前:
刷新后:
环境:
- “下一个”:“12.1.0”,
- “反应”:“17.0.2”,
- “@emotion/cache”:“^11.7.1”,
- “@emotion/react”:“^11.8.1”,
- “@emotion/server”:“^11.4.0”,
- “@emotion/styled”:“^11.8.1”,
- "@fontsource/roboto": "^4.5.3",
- "@mui/icons-material": "^5.4.4",
- "@mui/material": "^5.4.4",
- “@mui/styles”:“^5.4.2”
【问题讨论】:
-
您能分享任何重现此行为的代码框链接吗?
-
是的,codesandbox.io/s/throbbing-rain-72v10e 但是代码和框给了我一个错误“命令失败,代码 137”现在,可以了
-
您好,您是否发现了有关此问题的任何信息?
标签: reactjs material-ui next.js