如何在Material-UI中使用breakpoints配置theme spacing
问题
有没有办法使用断点定义主题间距(theme spacing)?类似如下实现方式:
spacing: { [defaultTheme.breakpoints.down('sm')]: 4 [defaultTheme.breakpoints.up('sm')]: 8 ... }
或者采用和排版(typography)一致的响应式配置逻辑?
我知晓可以使用rem单位实现,但该方案不符合我的使用需求。
解决方案
MUI 原生的spacing配置项本身不支持直接传入断点映射的格式,不过你可以通过两种方案实现需求,全程不需要依赖rem单位:
方案1:全局配置响应式spacing(和typography响应式逻辑一致)
第一步:创建theme时自定义各断点对应的spacing基准值
import { createTheme } from '@mui/material/styles'; const baseTheme = createTheme(); const theme = createTheme(baseTheme, { // 自定义响应式spacing全局配置 responsiveSpacing: { xs: 4, // 小于sm断点时,spacing基准为4px sm: 8, // sm及以上断点时,spacing基准为8px md: 10, // md及以上断点时,spacing基准为10px lg: 12, // lg及以上断点时,spacing基准为12px }, // 其他theme配置保持正常即可 });
第二步:封装一个全局调用的响应式spacing钩子
import { useTheme, useMediaQuery } from '@mui/material'; export const useResponsiveSpacing = (factor = 1) => { const theme = useTheme(); // 按断点优先级从高到低匹配 if (useMediaQuery(theme.breakpoints.up('lg'))) { return `${theme.responsiveSpacing.lg * factor}px`; } if (useMediaQuery(theme.breakpoints.up('md'))) { return `${theme.responsiveSpacing.md * factor}px`; } if (useMediaQuery(theme.breakpoints.up('sm'))) { return `${theme.responsiveSpacing.sm * factor}px`; } return `${theme.responsiveSpacing.xs * factor}px`; };
第三步:组件内直接调用即可自动适配断点
const DemoComponent = () => { // 传参2代表2倍基准值,不同断点下自动返回8px/16px/20px/24px const paddingVal = useResponsiveSpacing(2); return <div style={{ padding: paddingVal }}>测试内容</div>; };
方案2:无需修改theme,直接在sx属性中实现断点间距
如果你不需要全局统一的响应式spacing规则,也可以直接用MUIsx属性的原生断点语法实现:
import { Box } from '@mui/material'; const DemoComponent = () => { return ( <Box sx={{ // 数组按顺序对应xs/sm/md/lg四个断点的spacing倍数 padding: theme => [theme.spacing(1), theme.spacing(2), theme.spacing(2.5), theme.spacing(3)] }} > 测试内容 </Box> ) };
内容的提问来源于stack exchange,提问作者Kostya Tresko
相关产品推荐
相关产品推荐

