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

React与JavaScript中Null/Undefined值的显示异常问题

问题解决方法

问题根源在于你用模板字符串${}包裹了React元素——React元素本质是JavaScript对象,当你把它塞进模板字符串时,会自动调用对象的toString()方法,最终输出[Object Object]。

直接返回React元素即可,无需用模板字符串拼接:

const columns: GridColDef[] = [
  { field: "id", hide: true },
  {
    field: "col1",
    headerName: "Column 1",
    width: 150,
    renderCell({ value }) {
      if (value === null || value === undefined) {
        return <div style={{ fontStyle: "italic" }}>null</div>;
      }
      return String(value);
    }
  },
  {
    field: "col2",
    headerName: "Column 2",
    width: 150,
    renderCell({ value }) {
      if (value === null || value === undefined) {
        return <div style={{ fontStyle: "italic" }}>null</div>;
      }
      return String(value);
    }
  }
];

如果需要分别显示null和undefined,可以把返回的文本改成对应值:

return <div style={{ fontStyle: "italic" }}>{String(value)}</div>;

修改后,null/undefined会以斜体形式显示,空字符串和有效值也能正常渲染。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 17:52:40