You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求推荐兼容React 18的Material UI makeStyles()替代方案

React 18并发模式下Material-UI makeStyles()的替代方案

我正在开发一个React项目,此前一直使用Material-UI的makeStyles()函数为组件设置样式。但近期了解到makeStyles()并不兼容React 18的并发模式,而我计划在项目中使用该模式。
我希望找到Material-UI中具备类似makeStyles()功能、且兼容React 18的替代方案,理想方案需支持类似的样式定义方式,并可直接访问theme值。
当前使用makeStyles()的示例:

const useStyles = makeStyles((theme) => ({
  root: {
    marginLeft: theme.spacing(1),
  },
}));

const App = () => {
  const classes = useStyles();
  return <Typography className={classes.root}>{data.title}</Typography>;
}

以下是几个兼容React 18并发模式的替代方案,均支持访问MUI theme,且用法接近你当前的代码风格:

1. 使用MUI v5官方推荐的styled() API

这是MUI v5主推的样式方案,基于Emotion实现,完全兼容React 18并发模式,支持直接在样式定义中访问theme,同时封装性更强。

import { styled, Typography } from '@mui/material';

// 封装带样式的组件
const StyledTypography = styled(Typography)(({ theme }) => ({
  marginLeft: theme.spacing(1),
}));

const App = () => {
  // 直接使用封装后的组件,无需手动管理类名
  return <StyledTypography>{data.title}</StyledTypography>;
};

2. 封装自定义useStyles Hook(基于css())

如果偏好保持原有的"定义样式hook → 获取类名 → 绑定到组件"的流程,可以用@mui/system提供的css()函数结合useTheme封装自定义hook,和你原来的代码结构几乎一致:

import { css, useTheme, Typography } from '@mui/material';

// 自定义useStyles hook,和原makeStyles逻辑对齐
const useStyles = () => {
  const theme = useTheme();
  return {
    root: css({
      marginLeft: theme.spacing(1),
    }),
  };
};

const App = () => {
  const classes = useStyles();
  return <Typography className={classes.root}>{data.title}</Typography>;
};

3. 直接使用Emotion的css() Hook

由于MUI v5底层依赖Emotion,你也可以直接用Emotion的原生API来定义样式,同样能无缝访问MUI的theme:

import { useTheme } from '@mui/material';
import { css } from '@emotion/react';
import { Typography } from '@mui/material';

const useStyles = () => {
  const theme = useTheme();
  return {
    root: css`
      margin-left: ${theme.spacing(1)};
    `,
  };
};

const App = () => {
  const classes = useStyles();
  return <Typography className={classes.root}>{data.title}</Typography>;
};

方案选择建议

  • 优先选styled() API:符合MUI v5的设计理念,组件封装更彻底,代码更简洁。
  • 若要最大化复用原有代码结构,选自定义useStyles Hook方案,改动最小。

内容的提问来源于stack exchange,提问作者Amit Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 21:12:39