使用 react-window 渲染表行时如何处理“警告:validateDOMNesting(...): <tr> 不能作为 <div> 的子项出现。”

Posted

技术标签:

【中文标题】使用 react-window 渲染表行时如何处理“警告:validateDOMNesting(...): <tr> 不能作为 <div> 的子项出现。”【英文标题】:How to deal with "Warning: validateDOMNesting(...): <tr> cannot appear as a child of <div>. " when using react-window to render table rows 【发布时间】:2020-12-30 09:45:21 【问题描述】:

我正在使用react-window 创建带有react-table 7 的虚拟表(以及材料UI 表)。

我正在嵌入 FixedSizeList 而不是 TableBody。像这样的:

   <TableBody ...getTableBodyProps()>
    <FixedSizeList
      height=listHeight
      itemCount=rows.length
      itemSize=rowHeight
    >
     RenderRow
    </FixedSizeList>)
   </TableBody>

并且 RenderRow 返回 TableRows。像这样的:

 const RenderRow = React.useCallback(  ( index, style ) =>
 
     const row = rows[index];
     prepareRow(row);
     const rowProps = row.getRowProps();
     return (<TableRow
              ...row.getRowProps(
               style,
              ) />);
 

由于react-window的工作原理,它创建了几个divs来实现列表滚动,根据需要动态嵌入需要的TableRows,导致输出react js警告。

webpack-internal:///490:506 Warning: validateDOMNesting(...): &lt;tr&gt; cannot appear as a child of &lt;div&gt;

只是忽略这个警告,不是我想做的事情,因为它可能会导致其他警告不被注意到。 (我也不想在测试时使用发布版本)

那么是否可以防止发出此警告? 或者是否可以将react-window 用于表格行,而不会收到此警告?

更新: 尝试将innerElementType 设置为tbody 建议。

这会更改 FixedSizeList 呈现的内部 div。

来自:

<div style="position: relative; height: 96px; overflow: auto; will-change: transform; direction: ltr;">
<div style="height: 96px; width: 100%;">

<div style="position: relative; height: 96px; overflow: auto; will-change: transform; direction: ltr;">
<tbody style="height: 96px; width: 100%;">

所以现在包含在 tbody 中。

所以我想我还需要使用outerElementType 来更改外部div,以处理table 警告中的div,但我想不出任何有效的方法......

如果我不想包含thead,我可以将outerElementType 设置为table,将innerElementType 设置为tbody

【问题讨论】:

【参考方案1】:

FixedSizeList 接受 innerElementType prop 以让您指定要使用的 html 标记而不是 div。据我阅读the code 可以看出,它或多或少需要一个标签字符串。

您可能希望这个innerElementType 成为tbody,这意味着要重新处理父元素;我猜你不想继续使用TableBody

【讨论】:

感谢您的回答 + 到 FixedSizeList 文档的链接。我不知何故错过了。我正在尝试考虑一些可行的 outerElementType 和 innerElementType 组合。 进一步研究,似乎this GitHub issue 有一个好消息/坏消息组合:坏消息是react-window 库不能很好地处理表格,好消息是一位评论者建议alternative 似乎帮助其他人解决了同样的问题。

以上是关于使用 react-window 渲染表行时如何处理“警告:validateDOMNesting(...): <tr> 不能作为 <div> 的子项出现。”的主要内容,如果未能解决你的问题,请参考以下文章

Delphi Seattle 中运行时 DPI 更改后如何处理菜单缩放

如何处理触发器中的错误?

如何处理对象属性内的事件函数?

在redux返回结果之前如何处理渲染方法?

“不知道如何处理' nvcc 致命错误

使用MVVM框架时,如何处理在页面动态渲染完之后需要发生的事件呢?