MUIv5与tss-react SSR问题:CSS属性箭头函数表达式处理异常
MUI v5迁移中makeStyles插值SSR失效的解决方案
1. 继续使用@mui/styles兼容包
MUI v5保留了@mui/styles兼容包,完全支持原makeStyles的props插值写法,适配SSR场景:
- 安装兼容包:
npm install @mui/styles - SSR时需配置
ServerStyleSheets收集样式,避免样式异常:
import { ServerStyleSheets } from '@mui/styles'; import ReactDOMServer from 'react-dom/server'; import MyComponent from './MyComponent'; function renderToString() { const sheets = new ServerStyleSheets(); const html = ReactDOMServer.renderToString(sheets.collect(<MyComponent />)); const css = sheets.toString(); return ` <html> <head> <style id="jss-server-side">${css}</style> </head> <body>${html}</body> </html> `; }
2. 转用styled-components(已集成项目优先)
如果项目已引入styled-components,可将原makeStyles逻辑改写为styled组件,天然支持props传参且SSR友好:
import styled from '@mui/material/styles/styled'; import Typography from '@mui/material/Typography'; const StyledHeading = styled(Typography)(({ theme, isGreenBG }) => ({ color: isGreenBG ? theme.palette.common.white : theme.palette.primary.main, marginBottom: '15px', letterSpacing: 'normal', [theme.breakpoints.down('xs')]: { fontSize: '2rem', lineHeight: '2rem', }, })); // 组件内使用 export const MyComponent = ({ colorPalette }) => { const isGreenBG = colorPalette.toLowerCase() === COLORS.GREEN1; return <StyledHeading variant="h1" isGreenBG={isGreenBG}>Just an example</StyledHeading>; };
3. 手动适配tss-react
tss-react是MUI推荐替代makeStyles的方案,codemod无法自动转换时,手动改写即可支持props插值且兼容SSR:
- 安装包:
npm install tss-react - 改写原样式代码:
import { makeStyles } from 'tss-react/mui'; const useStyles = makeStyles()((theme, props) => ({ root: { backgroundColor: () => { let bgColor = "inherit"; if (props.colorPalette.toLowerCase() === COLORS.SAND) { bgColor = theme.palette.background.sand; } else if (props.isGreenBG) { bgColor = theme.palette.primary.main; } else { bgColor = theme.palette.common.white; } return bgColor; }, }, heading: { color: props.isGreenBG ? theme.palette.common.white : theme.palette.primary.main, marginBottom: `15px`, letterSpacing: `normal`, [theme.breakpoints.down(`xs`)]: { fontSize: `2rem`, lineHeight: `2rem`, }, }, // 其余样式按相同逻辑改写 })); // 组件使用方式不变 export const MyComponent = ({ colorPalette }) => { const isGreenBG = colorPalette.toLowerCase() === COLORS.GREEN1; const { classes } = useStyles({ isGreenBG, colorPalette }); return <h1 className={classes.heading}>Just an example</h1>; };
以上方案无需完全重写组件,可保留原有props驱动样式的逻辑,只需注意对应方案的SSR配置要求即可。
内容的提问来源于stack exchange,提问作者Logan Murphy
相关产品推荐
相关产品推荐

