【问题标题】:react table select rows - programmatically select rows based on input propsreact table select rows - 根据输入道具以编程方式选择行
【发布时间】:2021-12-27 11:37:49
【问题描述】:

我创建了一个反应表,其中包含this example 之后的选择行。 我正在尝试对其进行修改,以便在加载数据时,根据行数据的 included 值选中或取消选中相应的复选框。该值似乎无法识别,当我选中/取消选中一行时,onChange console.log 事件没有被触发。我做错了什么。

Heres my Sandbox Example

数据

[
  {
    systemId: 13,
    deqId: "25007",
    facilityId: 6487,
    sourceId: "WS002",
    sourceName: "GROVE SPRING",
    flowRate: 461,
    flowUom: "GPM   ",
    included: true
  },
  {
    systemId: 13,
    deqId: "25007",
    facilityId: 4742,
    sourceId: "WS004",
    sourceName: "WELL #1",
    flowRate: 1100,
    flowUom: "GPM   ",
    included: true
  },
  {
    systemId: 13,
    deqId: "25007",
    facilityId: 4743,
    sourceId: "WS005",
    sourceName: "100 W (WELL #2)                         ",
    flowRate: 800,
    flowUom: "GPM   ",
    included: true
  },
  {
    systemId: 13,
    deqId: "25007",
    facilityId: 4744,
    sourceId: "WS007",
    sourceName: "NORTH (WELL #3)                         ",
    flowRate: 900,
    flowUom: "GPM   ",
    included: true
  }
];

确定复选框

const IndeterminateCheckbox = React.forwardRef(
  ({ indeterminate, checked, name, ...rest }, ref) => {
    const defaultRef = React.useRef(checked);
    const resolvedRef = ref || defaultRef;

    React.useEffect(() => {
      resolvedRef.current.indeterminate = indeterminate;
      resolvedRef.current.checked = checked;
    }, [resolvedRef, indeterminate, checked]);

    return (
      <>
        <input
          type="checkbox"
          ref={resolvedRef}
          checked={checked}
          name={name}
          id={name}
          {...rest}
        />
      </>
    );
  }
);

反应表


function ReactTable({
  columns,
  data,
  handleCheckboxSelection,
  handleCheckboxStateChange
}) {
  // Use the state and functions returned from useTable to build your UI
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    footerGroups,
    rows,
    prepareRow,
    selectedFlatRows
  } = useTable(
    {
      columns,
      data
    },
    useRowSelect,
    (hooks) => {
      hooks.visibleColumns.push((columns) => [
        // Let's make a column for selection
        {
          id: "selection",
          // The header can use the table's getToggleAllRowsSelectedProps method
          // to render a checkbox
          Header: (
            { getToggleAllRowsSelectedProps },
            handleCheckboxStateChange
          ) => (
            <div>
              <IndeterminateCheckbox {...getToggleAllRowsSelectedProps()} />
            </div>
          ),
          // The cell can use the individual row's getToggleRowSelectedProps method
          // to the render a checkbox
          Cell: ({ row }) => (
            <div>
              <IndeterminateCheckbox
                name={row.original.sourceId}
                onChange={(row) => console.log(row.original)} //not firing
                checked={row.original.included}
                {...row.getToggleRowSelectedProps()}
              />
            </div>
          )
        },
        ...columns
      ]);
    }
  );

  // Render the UI for your table
  return (
    <>
      <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.slice(0, 10).map((row, i) => {
            prepareRow(row);
            return (
              <tr {...row.getRowProps()}>
                {row.cells.map((cell) => {
                  return (
                    <td {...cell.getCellProps()}>{cell.render("Cell")}</td>
                  );
                })}
              </tr>
            );
          })}
        </tbody>
        <tfoot>
          {footerGroups.map((group) => (
            <tr {...group.getFooterGroupProps()}>
              {group.headers.map((column) => (
                <td {...column.getFooterProps()}>
                  <b>{column.render("Footer")}</b>
                </td>
              ))}
            </tr>
          ))}
        </tfoot>
      </table>
      <button onClick={() => handleCheckboxSelection(selectedFlatRows)}>
        Save
      </button>
    </>
  );
}

表实现

const MyDataTable = ({
  data
}) => {

const handleCheckboxSelection = (array) => {
    console.log(array.map((d) => d.original));
  };

  const columns = React.useMemo(
    () => [
      {
        Header: "Source ID",
        accessor: "sourceId"
      },
      {
        Header: "Source Name",
        accessor: "sourceName"
      },
      {
        Header: "Flow Rate (GPM)",
        accessor: (d) => {
          return d.flowRate ? numberWithCommas(d.flowRate) : "";
        }
      }
    ],
    []
  );
  return (
    <ReactTable
      columns={columns}
      data={data}
      handleCheckboxSelection={handleCheckboxSelection}
    />
  );
};

【问题讨论】:

    标签: reactjs react-table-v7


    【解决方案1】:

    您添加到 IndeterminateCheckbox 的道具正在被覆盖。 row.getToggleRowSelectedProps() 返回一个对象:

    {
       onChange: function,
       checked: Boolean,
       title: String,
       indeterminate: Boolean,
       style: Object
    }
    

    这会覆盖您的属性。

    做你想做的事情的正确方法是使用 initialState.selectedRowIds property 来自 useRowSelect API。

    将您的数据映射到它们的included 值,然后将该数组作为 selectedRowIds 添加到 initialState。在 ReactTable.js 中:

    const selectedRowIds = data.map((d, ind) => d.included)
    const { 
      // etc 
    } = useTable(
      {
        columns,
        data,
        initialState: {selectedRowIds}
      },
      //etc
      ...columns
      }
    );
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-01
      • 1970-01-01
      • 2016-01-13
      • 1970-01-01
      相关资源
      最近更新 更多