如何让Material UI Switch组件在移动端垂直显示?
如何将Material UI Switch组件在移动端改为垂直布局
要实现Switch组件在移动端垂直显示,核心思路是通过CSS旋转Switch并调整容器的flex布局,具体操作如下:
步骤1:调整容器移动端布局
在useStyles的移动端断点中,将fabDiv设置为垂直flex布局,让内部的文字和Switch垂直排列:
[theme.breakpoints.down('sm')]: { fabDiv: { display: 'flex', flexDirection: 'column', alignItems: 'center', padding: '0.5rem 0.2rem' // 调整内边距适配垂直布局 } }
步骤2:添加Switch垂直样式
给Switch新增一个自定义类,在移动端通过transform: rotate(90deg)将其旋转为垂直方向,同时调整间距保证布局美观:
const useStyles = makeStyles((theme) => ({ // ... 原有fabDiv样式 switchVertical: { [theme.breakpoints.down('sm')]: { transform: 'rotate(90deg)', margin: '0.3rem 0' // 上下间距,让文字和开关对齐 } }, // ... 断点样式 }));
步骤3:修改组件引用
在Switch组件上添加这个自定义类:
<Switch checked={checked} onChange={onChange} className={classes.switchVertical} />
修改后的完整代码
import { makeStyles, createTheme, ThemeProvider, Switch } from '@mui/material'; const useStyles = makeStyles((theme) => ({ fabDiv: { position: 'absolute', top: theme.spacing(15), right: theme.spacing(2), padding: '0.2rem', textShadow: '0.06rem 0.06rem #000000', fontFamily: 'PT Sans Caption', boxShadow: '0rem 0.1rem 0.1rem #006bb3', borderRadius: '0.6rem', background: '#00BFFF', color: '#F8F8F8' }, switchVertical: { [theme.breakpoints.down('sm')]: { transform: 'rotate(90deg)', margin: '0.3rem 0' } }, [theme.breakpoints.down('sm')]: { fabDiv: { display: 'flex', flexDirection: 'column', alignItems: 'center', padding: '0.5rem 0.2rem' } } })); const theme = createTheme({ components: { MuiSwitch: { styleOverrides: { switchBase: { color: "#F8F8F8" }, colorPrimary: { "&.Mui-checked": { color: "#F8F8F8" } }, track: { opacity: 0.6, backgroundColor: "#F8F8F8", ".Mui-checked.Mui-checked + &": { opacity: 0.6, backgroundColor: "#F8F8F8" } } } } } }); const WeightConverter = (props) => { const { onChange, checked } = props; const classes = useStyles(); return ( <ThemeProvider theme={theme}> <div className={classes.fabDiv} > lb <Switch checked={checked} onChange={onChange} className={classes.switchVertical} /> kg </div> </ThemeProvider> ) }; export default WeightConverter;
说明
Material UI官方Switch组件没有内置垂直布局的配置项,通过CSS旋转是最直接的实现方式。旋转后Switch的交互逻辑保持不变,只是视觉上变为垂直方向,完全适配移动端需求。
内容的提问来源于stack exchange,提问作者Victor
相关产品推荐
相关产品推荐

