在React DataSheet Grid中动态添加列

问题描述 投票:0回答:1

我正在使用 React DataSheet Grid,我想知道是否可以动态添加列。我尝试使用下面的代码,但由于某种原因,它不起作用。

import React, { useState } from "react";
import {
  DataSheetGrid,
  textColumn,
  checkboxColumn,
  keyColumn,
} from "react-datasheet-grid";
import "react-datasheet-grid/dist/style.css";

const App = () => {
  const [data, setData] = useState([
    { active: true, firstName: "Elon", lastName: "Musk" },
  ]);

  const [columns, setColumns] = useState([
    { ...keyColumn("active", checkboxColumn), title: "Active" },
    { ...keyColumn("firstName", textColumn), title: "First Name" },
    { ...keyColumn("lastName", textColumn), title: "Last Name" },
  ]);

  const addColumn = () => {
    const newColumnKey = `column${columns.length + 1}`;
    const newColumn = {
      ...keyColumn(newColumnKey, textColumn),
      title: `Column ${columns.length + 1}`,
    };

    setColumns([...columns, newColumn]);

    setData((prevData) =>
      prevData.map((row) => ({
        ...row,
        [newColumnKey]: "", 
      }))
    );

  };

  return (
    <div>
      <button onClick={addColumn} style={{ marginBottom: "10px" }}>
        Add Column
      </button>
      <DataSheetGrid value={data} onChange={setData} columns={columns} />
    </div>
  );
};

export default App;

我希望当我调用 addColumn() 时将新列添加到网格中。

javascript reactjs arrays react-hooks react-table
1个回答
0
投票

像这样更新专栏

 setColumns((prevColumns) => [...prevColumns, newColumn]);
© www.soinside.com 2019 - 2024. All rights reserved.