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

如何为MUI v4 Grid组件实现基于断点的CSS平滑过渡效果

解决方案

核心问题原因:当给MUI v4的Grid item传递xl={false}时,组件会自动移除对应宽度样式甚至切换为display: none,没有中间宽度状态,自然无法触发CSS过渡。可以按以下步骤实现需求:

步骤1:编写适配MUI断点的过渡样式

通过MUI内置的makeStyles结合主题断点能力,定义带过渡效果的样式规则:

import { useState } from 'react';
import { Grid, Button, makeStyles } from '@material-ui/core';

const useStyles = makeStyles((theme) => ({
  gridItem: {
    // 全局配置宽度过渡效果
    transition: 'all 0.3s ease',
  },
  gridB: {
    overflow: 'hidden', // 隐藏时避免内容溢出
    // 小于xl断点时默认隐藏,可根据需求调整其他断点行为
    [theme.breakpoints.down('lg')]: {
      width: 0,
      padding: 0,
      flexGrow: 0,
    },
    [theme.breakpoints.up('xl')]: {
      // 状态控制宽度,xl=3对应宽度为25%
      width: props => props.showB ? 0 : '25%',
      padding: props => props.showB ? 0 : theme.spacing(2),
      flexGrow: props => props.showB ? 0 : 1,
    }
  }
}))

步骤2:调整Grid组件与状态逻辑

不要使用xl={false}的写法,改为通过自定义样式动态控制宽度,同时修正原代码的状态控制错误:

export default function GridTransitionDemo() {
  const [showB, setShowB] = useState(true);
  const classes = useStyles({ showB }); // 将状态传入样式生成器

  return (
    <>
      <Grid container direction="row" spacing={2}>
        <Grid 
          id="a" 
          item 
          className={classes.gridItem}
          // xl断点下同步适配宽度,showB为true时占12份即100%,为false时占9份即75%
          style={{ flexBasis: showB ? '100%' : '75%' }}
        >
          {children}
        </Grid>
        <Grid 
          id="b" 
          item 
          className={`${classes.gridItem} ${classes.gridB}`}
        >
          {otherchildren}
        </Grid>
      </Grid>
      <Button onClick={() => setShowB(prev => !prev)}>
        Show 1 or 2 items
      </Button>
    </>
  )
}

实现说明

  • 完全保留MUI的断点系统,所有宽度切换规则仅在xl断点以上生效,其他断点下b项默认隐藏
  • 通过动态控制width、padding、flexBasis属性,给元素提供了从0到25%的中间过渡状态,成功触发CSS过渡效果
  • 同步调整a项的宽度比例,避免切换过程中出现布局错乱

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 10:54:03