React中Material UI v5.2.7版本如何正确使用makeStyles?
MUI 5.2.7中makeStyles的正确替代方案
临时过渡方案(不推荐长期使用)
虽然@mui/styles在MUI v5中被标记为废弃,但如果需要临时过渡,可以按以下步骤操作:
- 安装依赖:
npm install @mui/styles # 或 yarn yarn add @mui/styles - 导入
makeStyles:import { makeStyles } from '@mui/styles';
注意:该包不会再更新新功能,长期建议迁移到官方推荐方案。
官方推荐的替代方案(优先选择)
MUI 5官方推荐以下几种样式方案来替代makeStyles:
1. 使用styled API
从@mui/material/styles导入styled创建样式化组件:
import { styled } from '@mui/material/styles'; import Button from '@mui/material/Button'; const StyledButton = styled(Button)(({ theme }) => ({ backgroundColor: theme.palette.primary.main, padding: theme.spacing(2), '&:hover': { backgroundColor: theme.palette.primary.dark, }, })); // 使用组件 <StyledButton>点击我</StyledButton>
2. 使用sx Prop
直接在MUI组件上使用sx prop,支持内联样式并自动适配主题:
import Button from '@mui/material/Button'; <Button sx={{ bgcolor: 'primary.main', p: 2, '&:hover': { bgcolor: 'primary.dark' }, }} > 点击我 </Button>
3. 结合Emotion的css Prop(项目已集成Emotion时)
如果项目已经使用Emotion,可以直接用它的css方案:
import { css } from '@emotion/react'; import Button from '@mui/material/Button'; const buttonStyles = css(({ theme }) => ({ backgroundColor: theme.palette.primary.main, padding: theme.spacing(2), '&:hover': { backgroundColor: theme.palette.primary.dark, }, })); <Button css={buttonStyles}>点击我</Button>
内容的提问来源于stack exchange,提问作者Madhav Badodiya
相关产品推荐
相关产品推荐

