2

I'm trying to add the windowing feature (from react-table virtualized-rows https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/virtualized-rows?file=/src/App.js:2175-2192)

to the Material-UI Enhanced Table (because I need the table of my application to be editable, with actions, filters, pagination..) from https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/material-UI-enhanced-table

both codes come from the official examples of react-table https://github.com/tannerlinsley/react-table/blob/5f67349a211c664dbc2eeaa9973c4d20f4e7e843/docs/examples/ui.md

Basically I started from the code of Material-UI Enhanced Table example and I added the FixedSizeList tag with its attributes and also the variable totalColumnsWidth taken from useTable()

From Chrome console I'm getting the error:

react.development.js:315 Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: array. Check the render method of List. in List (at App.js:134) react-dom.development.js:23965 Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. Check the render method of List.

What am I doing wrong?

 <FixedSizeList
            height={400}
            itemCount={10} 
            itemSize={35}
            width={totalColumnsWidth}
          >
   .....the table....
</FixedSizeList>

The current code is:


import React from "react";
import styled from "styled-components";
import {
  useTable,
  usePagination
} from "react-table";

import {
  FixedSizeList,
  FixedSizeGrid
} from "react-window";

import makeData from "./makeData";

const Styles = styled.div `
  padding: 1rem;

  table {
    border-spacing: 0;
    border: 1px solid black;

    tr {
      :last-child {
        td {
          border-bottom: 0;
        }
      }
    }

    th,
    td {
      margin: 0;
      padding: 0.5rem;
      border-bottom: 1px solid black;
      border-right: 1px solid black;

      :last-child {
        border-right: 0;
      }

      input {
        font-size: 1rem;
        padding: 0;
        margin: 0;
        border: 0;
      }
    }
  }

  .pagination {
    padding: 0.5rem;
  }
`;

// Create an editable cell renderer
const EditableCell = ({
  value: initialValue,
  row: {
    index
  },
  column: {
    id
  },
  updateMyData, // 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 onChange = (e) => {
    setValue(e.target.value);
  };

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

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

  return <input value = {
    value
  }
  onChange = {
    onChange
  }
  onBlur = {
    onBlur
  }
  />;
};

// Set our editable cell renderer as the default Cell renderer
const defaultColumn = {
  Cell: EditableCell,
};

// Be sure to pass our updateMyData and the skipPageReset option
function Table({
  columns,
  data,
  updateMyData,
  skipPageReset
}) {
  // For this example, we're using pagination to illustrate how to stop
  // the current page from resetting when our data changes
  // Otherwise, nothing is different here.
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    prepareRow,
    totalColumnsWidth,
    page,
    canPreviousPage,
    canNextPage,
    pageOptions,
    pageCount,
    gotoPage,
    nextPage,
    previousPage,
    setPageSize,
    state: {
      pageIndex,
      pageSize
    },
  } = useTable({
      columns,
      data,
      defaultColumn,
      // use the skipPageReset option to disable page resetting temporarily
      autoResetPage: !skipPageReset,

      // updateMyData isn't part of the API, but
      // anything we put into these options will
      // automatically be available on the instance.
      // That way we can call this function from our
      // cell renderer!
      updateMyData,
    },
    usePagination
  );

  // Render the UI for your table
  return ( <
    div >
    <
    table { ...getTableProps()
    } >
    <
    thead > {
      headerGroups.map((headerGroup) => ( <
        tr { ...headerGroup.getHeaderGroupProps()
        } > {
          headerGroup.headers.map((column) => ( <
            th { ...column.getHeaderProps()
            } > {
              column.render("Header")
            } < /th>
          ))
        } <
        /tr>
      ))
    } <
    /thead> <
    tbody { ...getTableBodyProps()
    } >
    <
    FixedSizeList height = {
      400
    }
    itemCount = {
      10
    } //test before was {rows.length}
    itemSize = {
      35
    }
    width = {
      totalColumnsWidth
    } >
    {
      page.map((row, i) => {
        prepareRow(row);
        return ( <
          tr { ...row.getRowProps()
          } > {
            row.cells.map((cell) => {
              return ( <
                td { ...cell.getCellProps()
                } > {
                  cell.render("Cell")
                } < /td>
              );
            })
          } <
          /tr>
        );
      })
    } <
    /FixedSizeList> <
    /tbody> <
    /table> <
    div className = "pagination" >
    <
    button onClick = {
      () => gotoPage(0)
    }
    disabled = {!canPreviousPage
    } > {
      "<<"
    } <
    /button>{" "} <
    button onClick = {
      () => previousPage()
    }
    disabled = {!canPreviousPage
    } > {
      "<"
    } <
    /button>{" "} <
    button onClick = {
      () => nextPage()
    }
    disabled = {!canNextPage
    } > {
      ">"
    } <
    /button>{" "} <
    button onClick = {
      () => gotoPage(pageCount - 1)
    }
    disabled = {!canNextPage
    } > {
      ">>"
    } <
    /button>{" "} <
    span >
    Page {
      " "
    } <
    strong > {
      pageIndex + 1
    } of {
      pageOptions.length
    } <
    /strong>{" "} <
    /span> <
    span >
    |
    Go to page: {
      " "
    } <
    input type = "number"
    defaultValue = {
      pageIndex + 1
    }
    onChange = {
      (e) => {
        const page = e.target.value ? Number(e.target.value) - 1 : 0;
        gotoPage(page);
      }
    }
    style = {
      {
        width: "100px"
      }
    }
    /> <
    /span>{" "} <
    select value = {
      pageSize
    }
    onChange = {
      (e) => {
        setPageSize(Number(e.target.value));
      }
    } >
    {
      [10, 20, 30, 40, 50].map((pageSize) => ( <
        option key = {
          pageSize
        }
        value = {
          pageSize
        } >
        Show {
          pageSize
        } <
        /option>
      ))
    } <
    /select> <
    /div> <
    /div>
  );
}

function App() {
  const columns = React.useMemo(
    () => [{
        Header: "Name",
        columns: [{
            Header: "First Name",
            accessor: "firstName",
          },
          {
            Header: "Last Name",
            accessor: "lastName",
          },
        ],
      },
      {
        Header: "Info",
        columns: [{
            Header: "Age",
            accessor: "age",
          },
          {
            Header: "Visits",
            accessor: "visits",
          },
          {
            Header: "Status",
            accessor: "status",
          },
          {
            Header: "Profile Progress",
            accessor: "progress",
          },
        ],
      },
    ], []
  );

  const [data, setData] = React.useState(() => makeData(20));
  const [originalData] = React.useState(data);
  const [skipPageReset, setSkipPageReset] = React.useState(false);

  // We need to keep the table from resetting the pageIndex when we
  // Update data. So we can keep track of that flag with a ref.

  // When our cell renderer calls updateMyData, we'll use
  // the rowIndex, columnId and new value to update the
  // original data
  const updateMyData = (rowIndex, columnId, value) => {
    // We also turn on the flag to not reset the page
    setSkipPageReset(true);
    setData((old) =>
      old.map((row, index) => {
        if (index === rowIndex) {
          return {
            ...old[rowIndex],
            [columnId]: value,
          };
        }
        return row;
      })
    );
  };

  // After data chagnes, we turn the flag back off
  // so that if data actually changes when we're not
  // editing it, the page is reset
  React.useEffect(() => {
    setSkipPageReset(false);
  }, [data]);

  // Let's add a data resetter/randomizer to help
  // illustrate that flow...
  const resetData = () => setData(originalData);

  return ( <
    Styles >
    <
    button onClick = {
      resetData
    } > Reset Data < /button> <
    Table columns = {
      columns
    }
    data = {
      data
    }
    updateMyData = {
      updateMyData
    }
    skipPageReset = {
      skipPageReset
    }
    /> <
    /Styles>
  );
}

export default App;
img {
  width: 100%;
}

.navbar {
  background-color: #e3f2fd;
}

.fa.fa-edit {
  color: #18a2b9;
}

.list-group-item.delete:hover {
  cursor: -webkit-grab;
  background-color: pink;
}

.list-group-item.update:hover {
  cursor: -webkit-grab;
  background-color: gainsboro;
}

.list-group-item.board:hover {
  cursor: -webkit-grab;
  background-color: gainsboro;
}

.fa.fa-minus-circle {
  color: red;
}

.landing {
  position: relative;
  /* background: url("../img/showcase.jpg") no-repeat; */
  background-size: cover;
  background-position: center;
  height: 100vh;
  margin-top: -24px;
  margin-bottom: -50px;
}

.landing-inner {
  padding-top: 80px;
}

.dark-overlay {
  background-color: rgba(0, 0, 0, 0.7);
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.card-form {
  opacity: 0.9;
}

.latest-profiles-img {
  width: 40px;
  height: 40px;
}

.form-control::placeholder {
  color: #bbb !important;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous" />
  <!--
      Notice the use of %PUBLIC_URL% in the tag above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
  <title>test</title>
</head>

<body>
  <div id="root"></div>
  <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start`.
      To create a production bundle, use `npm run build`.
    -->
</body>

</html>
4

1 回答 1

2

这里正在发生一些事情。首先,react-window 组件只接受一个函数/功能组件作为子组件。

在基本层面上,您必须将FixedSizeList标签之间的内容移动到函数中。所以,像:

// add useCallback here to prevent unnecessary re-renders
const RowRenderer = React.useCallback(({index, style}) => {
        const row = rows[index];
        prepareRow(row);
        return (
          // note the addition of style as an argument to getRowProps
          <tr {...row.getRowProps(style)}>
            {row.cells.map((cell) => {
              return (
                <td {...cell.getCellProps()}> {cell.render("Cell")}</td>
              );
            })}
          </tr>
        );
  // the useCallback dependency list
  },[prepareRow, rows]);

你会FixedSizeList像这样传递:

  <FixedSizeList
        height={400}
        itemCount={10} //test before was {rows.length}
        itemSize={35}
        width={totalColumnsWidth}
      >
        {RowRenderer}
   </FixedSizeList>

其次,据我了解,基本表格元素(tr、、、thtd)不适用于react-window中处理定位的方式。在您上面链接的演示中,您将看到窗口演示(与所有其他演示不同)使用divs. 所以你的标记现在看起来像:

// add useCallback here to prevent unnecessary re-renders
const RowRenderer = React.useCallback(({index, style}) => {
        const row = rows[index];
        prepareRow(row);
        return (
          // note the addition of style as an argument to getRowProps
          <div {...row.getRowProps(style)}>
            {row.cells.map((cell) => {
              return (
                <div {...cell.getCellProps()}> {cell.render("Cell")}</div>
              );
            })}
          </div>
        );
  // the useCallback dependency list
  },[prepareRow, rows]);

这适用于react-table,我认为您可以在每个Material-UI表格组件上设置component道具。即,等。这可能开始看起来像:<Table component='div'>...<TableCell component='div'>...

   // add useCallback here to prevent unnecessary re-renders
    const RowRenderer = React.useCallback(({index, style}) => {
            const row = rows[index];
            prepareRow(row);
            return (
              // note the addition of style as an argument to getRowProps
              <TableRow component='div' {...row.getRowProps(style)}>
                {row.cells.map((cell) => {
                  return (
                    <TableCell  component='div' {...cell.getCellProps()}> {cell.render("Cell")}</TableCell>
                  );
                })}
              </TableRow>
            );
      // the useCallback dependency list
      },[prepareRow, rows]);

至于将所有这些与 EnhancedTable 演示结合在一起,应该是可能的,如果有点棘手的话。我会把那个留给另一个答案。

于 2021-03-27T02:22:54.307 回答