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

如何在Material React Table中自定义无数据显示组件?

解决方案:material-react-table无数据时自定义表格体(保留列头)

由于noRecordsToDisplay仅支持字符串,要实现自定义组件渲染,可通过以下方式处理:

方法一:使用renderEmptyRows属性(推荐)

该属性是material-react-table专门用于自定义无数据状态的API,允许返回任意React组件作为表格体内容,且会自动保留列头。只需确保组件内的<td>设置colSpan为列总数,保证布局跨列显示。

步骤1:定义自定义空状态组件

const CustomEmptyState = ({ columnCount }) => (
  <tr>
    <td colSpan={columnCount} style={{ textAlign: 'center', padding: '2rem' }}>
      <div>
        <h3>暂无数据</h3>
        <p>点击下方按钮添加新数据</p>
        <button style={{ marginTop: '1rem', padding: '0.5rem 1rem', cursor: 'pointer' }}>
          添加数据
        </button>
      </div>
    </td>
  </tr>
);

步骤2:在表格组件中引入

<MaterialReactTable
  enableColumnResizing
  enablePinning
  enableColumnActions={false}
  enableColumnFilters={false}
  enablePagination={false}
  enableBottomToolbar={false}
  enableTopToolbar={false}
  enableFullScreenToggle={false}
  state={{ isLoading: false }}
  // 传入自定义组件,通过columns.length获取列总数
  renderEmptyRows={({ columns }) => <CustomEmptyState columnCount={columns.length} />}
  {...props}
/>

方法二:手动条件渲染(备选)

若需更灵活的结构控制,可手动判断数据源是否为空,结合表格的底层渲染逻辑自定义内容,但这种方式需要额外处理表格结构,推荐优先使用方法一。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 00:40:22