将 React-Window 添加到 Material-UI 增强表:类型无效 - 预期为字符串或类/函数,但得到:数组
Posted
技术标签:
【中文标题】将 React-Window 添加到 Material-UI 增强表:类型无效 - 预期为字符串或类/函数,但得到:数组【英文标题】:Adding React-Window to Material-UI Enhanced Table: type is invalid -- expected a string or a class/function but got: array 【发布时间】:2020-10-25 21:26:09 【问题描述】:我正在尝试添加窗口功能(来自 react-table virtualized-rows https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/virtualized-rows?file=/src/App.js:2175-2192)
来自 https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/material-UI-enhanced-table 的 Material-UI 增强表(因为我需要我的应用程序的表是可编辑的,带有操作、过滤器、分页..)
两个代码均来自react-tablehttps://github.com/tannerlinsley/react-table/blob/5f67349a211c664dbc2eeaa9973c4d20f4e7e843/docs/examples/ui.md官方示例
基本上我从 Material-UI Enhanced Table 示例的代码开始,我添加了 FixedSizeList 标记及其属性以及从 useTable() 获取的变量 totalColumnsWidth
从 Chrome 控制台我收到错误:
react.development.js:315 警告:React.createElement:类型无效 - 预期为字符串(用于内置组件)或类/函数(用于复合组件)但得到:数组。
检查List
的渲染方法。
在列表中(在 App.js:134)
react-dom.development.js:23965 未捕获错误:元素类型无效:需要一个字符串(对于内置组件)或类/函数(对于复合组件),但得到:对象。
检查List
的渲染方法。
我做错了什么?
<FixedSizeList
height=400
itemCount=10
itemSize=35
width=totalColumnsWidth
>
.....the table....
</FixedSizeList>
目前的代码是:
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>
【问题讨论】:
【参考方案1】:这里发生了一些事情。首先,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
、th
、td
等)不适用于 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 演示结合在一起而言,应该是可能的,虽然有点棘手。我会把那个留给另一个答案。
【讨论】:
以上是关于将 React-Window 添加到 Material-UI 增强表:类型无效 - 预期为字符串或类/函数,但得到:数组的主要内容,如果未能解决你的问题,请参考以下文章
react-window构造的虚拟列表使用react-resizable动态调整宽度和使用react-drag-listview拖拽变换列位置的问题
react-window构造的虚拟列表使用react-resizable动态调整宽度和使用react-drag-listview拖拽变换列位置的问题
记录React性能优化之“虚拟滚动”技术——react-window
使用 react-window 渲染表行时如何处理“警告:validateDOMNesting(...): <tr> 不能作为 <div> 的子项出现。”