You need to enable JavaScript to run this app. Material-ui DataGrid在temporary模式Drawer下筛选功能失效如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Material-ui DataGrid在temporary模式Drawer下筛选功能失效如何解决

问题原因

MUI 中variant="temporary"的 Drawer 组件本质是 Modal 组件的封装,默认开启交互限制:所有不在 Drawer 内部 DOM 树中的元素都会被标记为不可交互,无法响应点击、输入等操作。而 DataGrid 的筛选弹窗、排序弹窗等默认通过 Portal 挂载到全局document.body节点下,不属于 Drawer 的 DOM 子节点,因此触发了交互限制导致功能失效。
variant="permanent"的 Drawer 不属于 Modal 组件,没有上述交互限制,因此筛选功能可正常运行。

解决方案

方案1:调整 DataGrid 弹窗挂载节点(最推荐,不影响原有 accessibility 逻辑)

将 DataGrid 的所有 Popper 弹窗指定挂载到 Drawer 内部的 DOM 节点上,让弹窗属于 Drawer 的可交互范围。操作步骤:

  • 为 Drawer 内部的内容根节点创建 ref
  • 在 DataGrid 配置中指定 Popper 的挂载容器为该 ref 对应的 DOM 节点

代码示例:

import { useRef, useState } from 'react';
import Drawer from '@mui/material/Drawer';
import { DataGrid } from '@mui/x-data-grid';

function MyComponent() {
  const drawerContentRef = useRef(null);
  const [open, setOpen] = useState(false);

  return (
    <Drawer
      variant="temporary"
      open={open}
      onClose={() => setOpen(false)}
    >
      <div ref={drawerContentRef}>
        <DataGrid
          // 其他 DataGrid 配置项
          columns={columns}
          rows={rows}
          // DataGrid v5 用 componentsProps
          componentsProps={{
            popper: {
              container: drawerContentRef.current
            }
          }}
          // DataGrid v6 及以上版本替换为 slotProps
          // slotProps={{
          //   popper: {
          //     container: drawerContentRef.current
          //   }
          // }}
        />
      </div>
    </Drawer>
  )
}

方案2:关闭 Drawer 的交互限制(适合无严格 accessibility 要求的场景)

直接关闭 Drawer 继承自 Modal 的焦点锁定逻辑,允许外部元素响应交互:

<Drawer
  variant="temporary"
  open={open}
  onClose={handleClose}
  ModalProps={{
    disableEnforceFocus: true,
    disableAutoFocus: true,
    disableRestoreFocus: true
  }}
>
  <DataGrid {...yourDataGridProps} />
</Drawer>

该方案会破坏 Drawer 默认的模态焦点管理逻辑,有 accessibility 合规要求的场景不推荐使用

方案3:关闭 Drawer 的 Portal 挂载

给 Drawer 添加disablePortal属性,让 Drawer 内容直接挂载在父组件节点下而非全局 body,避免交互范围截断,该方案可能引发样式溢出、层级异常问题,优先级低于前两个:

<Drawer
  variant="temporary"
  open={open}
  onClose={handleClose}
  disablePortal
>
  <DataGrid {...yourDataGridProps} />
</Drawer>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 19:54:03