【问题标题】:How to make the row editable when clicking on an "Edit" button on a cell with react-table单击带有反应表的单元格上的“编辑”按钮时如何使行可编辑
【发布时间】:2021-01-22 01:54:17
【问题描述】:

我正在我的应用程序上使用react-table 制作交互式表格。

我的目标是制作一个在单击表格单元格中的按钮时每行可编辑的表格。

我设计了一个EditableCell,如下所示。

import React, {useState} from "react";

export const EditableCell = ({
                                 value: initialValue,
                                 row: Row,
                                 column: {id, editable, state},
                                 isEditing,
                                 updateItem, // This is a custom function that we supplied to our table instance
                             }) => {
    // We need to keep and update the state of the cell normally
    const [value, setValue] = React.useState(initialValue);
    const {index} = Row;

    const onChange = e => {
        setValue(e.target.value);
    };

    // We'll only update the external data when the input is blurred
    const onBlur = () => {
        updateItem(index, id, value);
    }

    // If the initialValue is changed external, sync it up with our state
    React.useEffect(() => {
        setValue(initialValue)
    }, [initialValue]);

    /**
     * Event handler to make a row editable.
     * @param e
     */
    const setRowEditing = (e) => {
        // TODO
    };

    let retObj = null;
    if (isEditing && editable) {
        switch (id) {
            default:
                retObj = <input className="input-edit w-100" value={value} onChange={onChange} onBlur={onBlur}/>;
                break;
        }
    } else {
        switch (id) {
            case 'action_btn':
                retObj = <>
                    <button className="btn btn-sm btn-info btn-sm-td" onClick={setRowEditing}>{ isEditing? "Save" : "Edit"}</button>
                </>;
                break;
            default:
                retObj = <div>{value}</div>;
                break;
        }
    }
    return retObj;
}

export const defaultColumn = {
    Cell: EditableCell,
};

而我的表格的定义是:(我使用了我的 EditableCell 组件)

export default function Table({ columns, data, updateItem }) {

    // Use the useTable Hook to send the columns and data to build the table
    const {
        getTableProps, // table props from react-table
        getTableBodyProps, // table body props from react-table
        headerGroups, // headerGroups, if your table has groupings
        rows, // rows for the table based on the data passed
        prepareRow // Prepare the row (this function needs to be called for each row before getting the row props)
    } = useTable({
        columns,
        data,
        defaultColumn,
        updateItem,
    }, useBlockLayout, useRowState);

    /*
      Render the UI for your table
      - react-table doesn't have UI, it's headless. We just need to put the react-table props from the Hooks, and it will do its magic automatically
    */
    return (
        <table className="data-table" {...getTableProps()}>
            <thead>
            {headerGroups.map(headerGroup => (
                <tr {...headerGroup.getHeaderGroupProps()}>
                    {headerGroup.headers.map(column => (
                        <th {...column.getHeaderProps()}>{column.render("Header")}</th>
                    ))}
                </tr>
            ))}
            </thead>
            <tbody {...getTableBodyProps()}>
            {rows.map((row, i) => {
                prepareRow(row);
                return (
                    <tr {...row.getRowProps()}>
                        {row.cells.map(cell => {
                            return <td {...cell.getCellProps()}>{cell.render("Cell")}</td>;
                        })}
                    </tr>
                );
            })}
            </tbody>
        </table>
    );
};

setRowEditing 函数中,我将更改当前行或其单元格的状态,以便将行中的单元格呈现为输入字段或其他内容。

但我不知道如何正确更改状态。

您能就此提出建议吗?

【问题讨论】:

  • 你有这个场景的工作示例吗?我正在尝试实现类似但无法实现的东西:(如果您能分享一个有关如何解决问题的工作示例,我将不胜感激
  • 嗨,我也在尝试做同样的事情,但卡在更新数据中......如果有人解决了这种类型的例子,请分享谢谢@NickDiv
  • @suraj 我一定会的。我个人更改了库,因为业务需求随时间而变化,但我仍然会再试一次,看看我是否可以让它工作。

标签: reactjs react-table-v7


【解决方案1】:

在您传递给反应表的列数组中,您需要创建一个按钮,该按钮的 onClick 函数需要回调来编辑您的数据以添加一个isEditing: true,以便您处理将行转换为从表格外部编辑模式。无需在可编辑单元格中使用setRowEditing

使用'isEditing'属性设置表格数据的功能

const handleClickEditRow = (rowIndex) => {
    setTableData(prev => prev.map((r, index) => ({...r, isEditing: rowIndex === index})))
}

在您的专栏中

{
    accessor: '[editButton]',
    Cell: (cellObj) => <button onClick={() => handleClickEditRow(cellObj.row.index)}>Edit</button>
}

【讨论】:

  • 感谢您的解决方案,我做了同样的事情,但它的编辑列不是行。经过一些代码更改,我正在编辑行,但仍然面临更新数据的问题
  • “[editButton]”是什么意思?它只是一个帮助读者的任意字符串吗?还是有什么特别的?
猜你喜欢
  • 2021-01-03
  • 2016-01-19
  • 2018-07-27
  • 1970-01-01
  • 2014-10-05
  • 1970-01-01
  • 2014-06-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多