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

Material UI Alert Dialog背景为何显示为黑色?

解决Material UI DataGrid内弹出Dialog背景变黑的问题

问题原因

你把<Dialog>组件放在了DataGrid的renderCell函数内部,每个表格单元格都会渲染一个Dialog,既造成组件冗余,又会因DataGrid单元格的样式继承、层级冲突导致Dialog背景样式异常。

修复方案

将Dialog从单元格渲染逻辑中移出,放到组件顶层位置,通过状态统一管理Dialog的显示状态和当前要删除的行ID:

修改后的完整代码

import { useState } from 'react';
import { DataGrid, Dialog, DialogTitle, DialogActions, Button } from '@mui/material';
import DeleteOutlineIcon from '@mui/icons-material/DeleteOutline';
import { Link } from 'react-router-dom';

export default function PostList() {
  const [openAD, setOpenAD] = useState(false);
  const [currentDeleteId, setCurrentDeleteId] = useState(null);

  const handleClickOpenAD = (id) => {
    setCurrentDeleteId(id);
    setOpenAD(true);
  };

  const handleCloseAD = () => {
    setOpenAD(false);
    setCurrentDeleteId(null);
  };

  const handleDelete = (id) => {
    // 在此处编写你的删除业务逻辑
    console.log('执行删除,ID:', id);
    handleCloseAD();
  };

  const columns = [
    { field: "_id", headerName: "ID", width: 90 },
    {
      field: "action",
      headerName: "操作",
      width: 150,
      renderCell: (params) => {
        return (
          <div>
            <Link to={`/post/${params.row._id}`}>
              <button>编辑</button>
            </Link>
            <DeleteOutlineIcon
              onClick={() => handleClickOpenAD(params.row._id)}
              style={{ cursor: 'pointer', marginLeft: '8px' }}
            />
          </div>
        );
      },
    },
  ];

  // 替换为你的实际数据源
  const posts = [];

  return (
    <>
      <DataGrid
        rows={posts}
        getRowId={(row) => row._id}
        disableSelectionOnClick
        columns={columns}
        pageSize={8}
        checkboxSelection
      />
      {/* 统一渲染单个Dialog,避免重复和样式冲突 */}
      <Dialog
        open={openAD}
        onClose={handleCloseAD}
        aria-labelledby="alert-dialog-title"
        aria-describedby="alert-dialog-description"
      >
        <DialogTitle id="alert-dialog-title">
          {"确定要删除这条帖子吗?"}
        </DialogTitle>
        <DialogActions>
          <Button onClick={handleCloseAD}>取消</Button>
          <Button onClick={() => handleDelete(currentDeleteId)} autoFocus>
            确定
          </Button>
        </DialogActions>
      </Dialog>
    </>
  );
}

额外样式调整(若需)

如果Dialog的遮罩层背景仍有异常,可通过BackdropProps自定义背景样式:

<Dialog
  // 保留原有属性
  BackdropProps={{
    style: { backgroundColor: 'rgba(0, 0, 0, 0.3)' } // 设置半透明遮罩
  }}
>
  {/* Dialog内容 */}
</Dialog>

内容的提问来源于stack exchange,提问作者sultan.h

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 16:20:47