如何根据反应中的 firestore 中的值设置复选框的默认状态 table

How can I set the default state of a checkbox based on value in firestore in react table

如何根据 React 中 firestore 的值设置复选框的默认状态 Table。 抱歉,如果问题有点基础。我已经通读了官方文档,并不能真正理解如何去做,我也看了很多其他的例子。

我想在页面加载时检查 firestore 文档中的值,然后设置复选框的默认值。我还希望用户能够 check/uncheck 它然后将更新文档中的该字段。

我在文档中看过这个 initialState.selectedRowIds: Object<rowId: Boolean> 但无法弄清楚如何让它工作或还需要连接什么。

如有任何帮助,我们将不胜感激。

下面是我的实现。

    import React from "react";
import {
  useTable,
  useFlexLayout,
  useFilters,
  useGlobalFilter,
  useRowSelect
} from "react-table";
import _ from "lodash";
// noinspection ES6CheckImport
import { useHistory } from "react-router-dom";
import Table from "react-bootstrap/Table";

// Define a default UI for filtering
function GlobalFilter({
  preGlobalFilteredRows,
  globalFilter,
  setGlobalFilter
}) {
  return (
    <span>
      <input
        value={globalFilter || ""}
        onChange={e => {
          setGlobalFilter(e.target.value || undefined); // Set undefined to remove the filter entirely
        }}
        placeholder={" Search by any criteria"}
        style={{
          fontSize: "2.0rem",
          width: "100%"
        }}
      />
    </span>
  );
}

   
export const RecordTable = ({ forms }) => {
  const data = forms;
  let history = useHistory();

  const columns = React.useMemo(
    () => [
      {
        Header: "Disclaimer Form Records",
        columns: [
          {
            Header: "Active",
            accessor: "active",
            width: 75,
            maxWidth: 75,
            maxHeight: 50,
            Cell: ({ row, column }) => (
              <div
                style={{
                  fontSize: "50px",
                  textAlign: "center",
                  display: "flex",
                  justifyContent: "center",
                  alignItems: "center",
                  width: "100%",
                  height: "100%"
                }}
                onClick={event => {
                  event.stopPropagation();
                  console.log("div OnClick");
                }}>
                <input
                  type="checkbox"
                  onClick={event => {
                    event.stopPropagation();
                    console.log("checkedIn Clicked: ", column);
                  }}
                  {...row.getToggleRowSelectedProps}
                />
              </div>
            )
          },
          {
            Header: "Time In",
            accessor: "timeIn"
          },
          {
            Header: "Time Out",
            accessor: "timeOut"
          },
          {
            Header: "€ Price",
            accessor: "totalGroupPrice",
            disableFilters: true,
            disableSortBy: true
          },
          {
            Header: "Shoebox",
            accessor: "shoeboxNumber"
          }
        ]
      }
    ],
    []
  );

  const defaultColumn = React.useMemo(
    () => ({
      //minWidth: 20,
      maxWidth: 150,
      width: 120
    }),
    []
  );

  const rowOnClick = (rowObject, column) => {
    history.push("/viewform", { ...rowObject.original });
  };

  // Use the state and functions returned from useTable to build your UI
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
    state,
    preGlobalFilteredRows,
    setGlobalFilter,
    setHiddenColumns
  } = useTable(
    {
      columns,
      data,
      defaultColumn,
    },
    useFilters,
    useGlobalFilter,
    useFlexLayout,
    useRowSelect
  );

  React.useEffect(() => {
    // for each column who's data is null, hide that column.

    let emptyColumns = [];

    _.forEach(data[0], function(value, key) {
      if (value === "") emptyColumns.push(key);
    });

    emptyColumns.push("parentEmailAddress");

    setHiddenColumns(emptyColumns);
  }, [setHiddenColumns, columns]);

  // Render the UI for your table
  return (
    <div>
      <div>Records: {rows.length}</div>
      <GlobalFilter
        preGlobalFilteredRows={preGlobalFilteredRows}
        globalFilter={state.globalFilter}
        setGlobalFilter={setGlobalFilter}
      />

      <div
        style={{
          height: 500,
          border: "2px solid grey",
          borderRadius: "5px",
          overflow: "scroll"
        }}>
        <Table striped bordered hover responsive={"md"} {...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({
                    onClick: () => rowOnClick(row)
                  })}>
                  {row.cells.map(cell => {
                    return (
                      <td {...cell.getCellProps()}>{cell.render("Cell")}</td>
                    );
                  })}
                </tr>
              );
            })}
          </tbody>
        </Table>
      </div>
    </div>
  );
};

您可以在 useTable 中使用 initialState,例如 -

useTable({
    columns,
    data,
    defaultColumn,
    initialState: {
        selectedRowIds: {
            "row_1": true,
            "row_5": true
        }
    }
}

虽然可能不是最推荐的方式。

这对我有用:

我从 firestore 中读取了一个布尔值,然后将其传递给复选框。 每当我 check/uncheck 复选框时,我都有一个功能可以切换 firestore 中的值,并且我有一个快照功能可以订阅任何更改,因此会自动更新实际的复选框。

<input type="checkbox" checked={isChecked}