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

自定义样式的MUI Drawer设置temporary变体时无法打开如何解决

问题根因

你在封装自定义样式的Drawer时,shouldForwardProp配置过滤了open属性,导致该属性无法被传递到底层原生MUI Drawer组件:

  • permanent变体的Drawer默认常驻渲染,仅靠样式控制宽度变化,因此即使拿不到open属性,也能通过你注入到styled组件的open变量控制样式,正常展示。
  • temporary变体的Drawer显隐逻辑完全依赖传入的open属性,属性被拦截后永远处于关闭状态,无法正常打开。

修复方案

调整styles.tsx中styled组件的配置,允许open属性透传给底层MUI Drawer,同时可以新增变体判断,只对非temporary变体应用自定义宽度动画逻辑,避免和temporary的默认动画冲突:

// 修复后的styles.tsx
import {styled} from '@mui/material';
import {Theme, CSSObject} from '@mui/material/styles';
import MuiDrawer from '@mui/material/Drawer';

const drawerWidth = 240;

const openedMixin = (theme: Theme): CSSObject => ({
  backgroundColor: 'green',
  width: drawerWidth,
  transition: theme.transitions.create('width', {
    easing: theme.transitions.easing.sharp,
    duration: theme.transitions.duration.enteringScreen,
  }),
  overflowX: 'hidden',
});

const closedMixin = (theme: Theme): CSSObject => ({
  transition: theme.transitions.create('width', {
    easing: theme.transitions.easing.sharp,
    duration: theme.transitions.duration.leavingScreen,
  }),
  overflowX: 'hidden',
  width: `calc(${theme.spacing(7)} + 1px)`,
  [theme.breakpoints.up('sm')]: {
    width: `calc(${theme.spacing(8)} + 1px)`,
  },
});

export const Drawer = styled(MuiDrawer, {
  // 不过滤open属性,透传给原生MuiDrawer
  shouldForwardProp: (prop) => true
})(
  ({theme, open, variant}) => {
    // temporary 变体用默认显隐逻辑,只保留自定义样式
    if (variant === 'temporary') {
      return {
        '& .MuiDrawer-paper': {
          backgroundColor: 'green',
          width: drawerWidth
        }
      }
    }
    // permanent/persistent 变体走自定义宽度动画逻辑
    return {
      width: drawerWidth,
      flexShrink: 0,
      whiteSpace: 'nowrap',
      boxSizing: 'border-box',
      ...(open && {
        ...openedMixin(theme),
        '& .MuiDrawer-paper': openedMixin(theme),
      }),
      ...(!open && {
        ...closedMixin(theme),
        '& .MuiDrawer-paper': closedMixin(theme),
      }),
    }
  },
)

修复后两种变体都可以正常工作,原有自定义样式不会受影响。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 14:54:03