jquery 交换React Aggrid中的行数据和列数据

gmxoilav  于 2023-08-04  发布在  jQuery
关注(0)|答案(1)|浏览(115)

使用react ag-grid以表格形式显示数据。
尝试交换下面的行和列数据,但没有工作。

import React, { useState } from 'react';
import { AgGridReact } from 'ag-grid-react';

import 'ag-grid-community/styles/ag-grid.css';
import 'ag-grid-community/styles/ag-theme-alpine.css';

const App = () => {
   const [rowData] = useState([
      {make: "Toyota", model: "Celica", price: 35000},
      {make: "Ford", model: "Mondeo", price: 32000},
      {make: "Porsche", model: "Boxster", price: 72000}
   ]);

const [columnDefs] = useState([
    { field: 'make' },
    { field: 'model' },
    { field: 'price' }
]);

return (
    <div className="ag-theme-alpine" style={{height: 400, width: 600}}>
        <AgGridReact
            rowData={rowData}
            columnDefs={columnDefs}>
        </AgGridReact>
    </div>
);
};

export default App;

字符串
预期采用下表格式

Make       Toyota      Ford      Porsche
Model      Celica      Mondeo    Boxster
price      35000       32000     72000

zlhcx6iw

zlhcx6iw1#

我认为这是一个黑客解决方案,但在我看来,在react-ag-grid中没有内置的方法来转置数据。因此,您可以尝试使用自定义函数转置数据。
举例来说:

const transposeData = (data, columns) => {
  const colNames = columns.map((col) => col.field);
  const transposed = colNames.map((colName) => {
    const obj = { name: colName };
    data.forEach((row, index) => {
      obj[index] = row[colName];
    });
    return obj;
  });
  return transposed;
};

const App = () => {
  /* define rowData and columnDefs */

  const transposedData = transposeData(rowData, columnDefs);
  const transposedColumns = [
    { field: "name" },
    ...rowData.map((row, index) => ({ field: index.toString() }))
  ];

  return (
    <div className="ag-theme-alpine" style={{ height: 400, width: 600 }}>
      <AgGridReact
        rowData={transposedData}
        columnDefs={transposedColumns}
        defaultColDef={{ width: 150 }}
        headerHeight={0}
      ></AgGridReact>
    </div>
  );
};

export default App;

字符串
你可以在这里看到整个例子:codesandbox.io

相关问题