【问题标题】:MUI DataGrid renderCell not displaying requested dataMUI DataGrid renderCell 不显示请求的数据
【发布时间】:2023-02-01 05:35:17
【问题描述】:

我正在尝试呈现 DataGrid (MUI) 并让其中一列包含指向另一个 React 路由器页面的链接。

以下代码未正确显示 MACID (params.value.macid)

const columns = [
{ field: 'macid', headerName: 'MACID', width: 250,
    renderCell: (params: GridRenderCellParams<String>) => (
      <strong>
        {params.value.macid}
        <a href="#" onClick={() => HandleDeviceClick(params.value.macid)}>GO</a>
      </strong>
    ) },

但是,如果我使用此代码,它将显示 MACID:

const columns = [
{ field: 'macid', headerName: 'MACID', width: 250,
    renderCell: (params: GridRenderCellParams<String>) => (
      params.value.macid
    ) },

更多构建行的代码...

for (var x in props.statsData) {
    if (props.statsData[x].cpu_us === null) {
        cpu = 0;
    } else {
        cpu = parseInt(props.statsData[x].cpu_us);
    }
    if (props.statsData[x].ramused === null) {
        ram = 0;
    } else {
        ram = parseInt(props.statsData[x].ramused);
    }
    if (props.statsData[x].disk1used === null) {
        disk = 0;
    } else {
        disk = parseInt(props.statsData[x].disk1used);
    }
    if (props.statsData[x].temperature === null) {
        temp = 0;
    } else {
        temp = parseInt(props.statsData[x].temprature);
    }
  rows.push(createData(counter, props.statsData[x].deviceID, cpu, ram, disk, temp))
  counter += 1;

}

function createData(id, macid, cpu, ram, disk, temperature) {
return {
  id,
  macid,
  cpu,
  ram,
  disk,
  temperature,
};

}

<div style={{ height: 800, width: '100%' }}>
  <DataGrid
    rows={rows}
    columns={columns}
    pageSize={25}
    rowsPerPageOptions={[25]}
  />
</div>

【问题讨论】:

  • 要使用链接、按钮或任何其他操作,请使用type: actionsgetActions 功能。 mui.com/x/react-data-grid/column-definition/#special-properties
  • @PrashantJangam 它在页面渲染时自动执行 onClick(在 getActions 中)内的代码,你知道为什么吗?
  • 尝试在 onclick onClick={()=&gt;yourFunction} 中使用箭头函数

标签: reactjs material-ui


【解决方案1】:

您不能直接在 renderCell 函数中使用 hook

如果你想在 renderCell 函数中使用钩子,你应该将它用作组件

对于您的示例,它看起来像这样

const Alink = (props) => {
  const [handleDeviceClick, setHandleDeviceClick] = useState(0);

  return (
    <a href="#" onClick={() => setHandleDeviceClick(props.macid)}>GO</a>
  );
};

const column = {
  // ...other properties,
  renderCell: () => ( 
      <strong>
        {params.value.macid}
        <Alink macid={params.value.macid}/>
      </strong>)
,
};

你也可以阅读这个: Using hooks inside a renderer

【讨论】:

    猜你喜欢
    • 2023-03-21
    • 2021-11-30
    • 1970-01-01
    • 2022-07-20
    • 1970-01-01
    • 2012-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多