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

如何对MUI X Data Grid的布尔类型单元格进行条件格式化?

MUI X Data Grid 布尔单元格条件格式化的多种实现方式

当然不是只能通过cellRenderer实现布尔类型单元格的条件格式化,根据需求复杂度,有几种更简洁或灵活的方案:

  • 方案1:cellClassName + 条件样式(适合简单样式需求)
    通过列定义的cellClassName属性,根据单元格值返回不同类名,再配合CSS定义样式,既能实现颜色、图标等效果,还能保持代码简洁。

    示例代码:

    const columns: GridColumns = [
      {
        field: 'isPaid',
        headerName: '是否支付',
        type: 'boolean',
        width: 140,
        editable: true,
        // 根据值返回对应类名
        cellClassName: (params) => params.value ? 'paid-status' : 'unpaid-status',
      },
    ];
    

    对应的CSS:

    .paid-status {
      color: #2e7d32;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .paid-status::before {
      content: '✅';
      margin-right: 6px;
    }
    
    .unpaid-status {
      color: #c62828;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .unpaid-status::before {
      content: '❌';
      margin-right: 6px;
    }
    
  • 方案2:valueFormatter 内联渲染(轻量自定义)
    如果不需要单独写CSS,可以用valueFormatter直接返回带样式的JSX,快速实现简单的图标+文本组合:

    const columns: GridColumns = [
      {
        field: 'isPaid',
        headerName: '是否支付',
        type: 'boolean',
        width: 140,
        editable: true,
        valueFormatter: (params) => {
          const [icon, text, color] = params.value 
            ? ['✅', '已支付', '#2e7d32'] 
            : ['❌', '未支付', '#c62828'];
          return (
            <span style={{ color, display: 'flex', alignItems: 'center', gap: 6, justifyContent: 'center' }}>
              {icon}
              {text}
            </span>
          );
        },
      },
    ];
    
  • 方案3:自定义renderCell组件(复杂场景推荐)
    当需要更复杂的布局、交互(比如hover效果、额外按钮)时,自定义单元格组件并通过renderCell引入,逻辑更清晰且可复用:

    // 自定义布尔状态单元格组件
    const BooleanStatusCell = (params: GridRenderCellParams<boolean>) => {
      const isPaid = params.value;
      return (
        <div style={{ 
          display: 'flex', 
          alignItems: 'center', 
          justifyContent: 'center', 
          gap: 8,
          padding: '4px 0'
        }}>
          <span style={{ color: isPaid ? '#2e7d32' : '#c62828', fontSize: 18 }}>
            {isPaid ? '✅' : '❌'}
          </span>
          <span style={{ fontWeight: isPaid ? 500 : 400 }}>
            {isPaid ? '已支付' : '未支付'}
          </span>
        </div>
      );
    };
    
    // 列定义中使用
    const columns: GridColumns = [
      {
        field: 'isPaid',
        headerName: '是否支付',
        type: 'boolean',
        width: 140,
        editable: true,
        renderCell: BooleanStatusCell,
      },
    ];
    

总结

  • 简单样式需求:优先选cellClassName+CSS,性能好且易维护;
  • 轻量自定义:valueFormatter快速实现,无需额外文件;
  • 复杂交互/布局:自定义renderCell组件,逻辑解耦且可复用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 03:35:27