NextJS App Router中MUI v5 makeStyles初始渲染后加载问题求助
Next.js App Router + MUI 5.14 中 makeStyles 样式延迟加载问题
使用最新版Next.js App Router及稳定版MUI 5.14时,已参照MUI文档完成配置,MUI组件可正常渲染,但采用JSS方案的makeStyles时,初始页面无对应样式,约0.5秒后样式才正常显示。
核心代码
app/layout.js
export default function RootLayout({ children }) { return ( <html lang="en"> <body className={inter.className}> <ThemeRegistry options={{ key: 'mui' }}> {children} </ThemeRegistry> </body> </html> ); }
app/ThemeRegistry.js
export default function ThemeRegistry(props) { const { options, children } = props; const [{ cache, flush }] = React.useState(() => { const cache = createCache(options); cache.compat = true; const prevInsert = cache.insert; let inserted = []; cache.insert = (...args) => { const serialized = args[1]; if (cache.inserted[serialized.name] === undefined) { inserted.push(serialized.name); } return prevInsert(...args); }; const flush = () => { const prevInserted = inserted; inserted = []; return prevInserted; }; return { cache, flush }; }); useServerInsertedHTML(() => { const names = flush(); if (names.length === 0) { return null; } let styles = ''; for (const name of names) { styles += cache.inserted[name]; } return ( <style key={cache.key} data-emotion={`${cache.key} ${names.join(' ')}`} dangerouslySetInnerHTML={{ __html: styles, }} /> ); }); return ( <CacheProvider value={cache}> <ThemeProvider theme={theme}> <CssBaseline /> {children} </ThemeProvider> </CacheProvider> ); }
app/page.js
export default function Home() { return <HomePage />; }
app/home-page.js
'use client'; import useStyles from './styles'; export default function HomePage() { const classes = useStyles(); return ( <Box className={classes.root}> ....components etc.... </Box> ) }
app/styles.js(makeStyles 导出文件)
import { makeStyles } from '@mui/styles'; const useStyles = makeStyles((theme) => ({ root: {}, ...otherStyles etc... })); export default useStyles;
页面状态对比
客户端执行
makeStyles前的页面状态:
约0.5秒后
makeStyles加载完成,样式正常显示:
内容的提问来源于stack exchange,提问作者Travis Delly
相关产品推荐
相关产品推荐

