不变违规:使用 Link 和表格时的 findComponentRoot

Invariant Violation: findComponentRoot when using Link & Tables

我正在使用 react-router 进行路由选择。我有一个 table 并且我希望这些行可以点击。

所以我有:

<table className="table table-hover table-bordered" cellSpacing="0" width="100%">
<thead>
<tr>
    <th>ID</th>
    <th>GUID</th>
    <th>Patch Name</th>
    <th>Description</th>
    <th>Creation Date</th>
</tr>
</thead>

<tbody>
{patches.map(function (patch) {
    return (
        <tr className="cursor-pointer">
            <Link to="patch" params={{patchId:patch.id}}>
                <td>{patch.id}</td>
                <td>{patch.guid}</td>
                <td>{patch.name}</td>
                <td>{patch.description}</td>
                <td>{moment(patch.creation_date).format('MMMM Do YYYY')}</td>
            </Link>
        </tr>
    );
})}
</tbody>
</table>   

单击一行后,我得到

Error: Invariant Violation: findComponentRoot(..., .0.2.0.0.0.0.0.0.1.0.1.0.0): Unable to find element. This probably means the DOM was unexpectedly mutated (e.g., by the browser), usually due to forgetting a when using tables, nesting tags like ,

, or , or using non-SVG elements in an parent. Try inspecting the child nodes of the element with React ID ``.

如果我将 <Link> 移动到 <tr> 之前,即:

<Link to="patch" params={{patchId:patch.id}}>
    <tr className="cursor-pointer">
        <td>{patch.id}</td>
        <td>{patch.guid}</td>
        <td>{patch.name}</td>
        <td>{patch.description}</td>
        <td>{moment(patch.creation_date).format('MMMM Do YYYY')}</td>
    </tr>
</Link>

然后它工作正常,但是 table CSS 完全搞砸了。怎么回事?

<Link> 呈现 <a> 元素,但 a <tr> element only accepts <th> or <td> elements as children.

<tbody> and <table> 也是如此,它只接受 HTML 元素的子集作为子元素。

您的浏览器将自动尝试修复您的 HTML。 React 不知道这种行为,当 DOM 结构不符合其预期时将抛出。正如错误指出的那样,这通常发生在您的 render 方法中输出无效的 HTML 结构时。

如果您希望整个 <tr> 充当 link,您应该在每个 table 单元格中渲染一个 link。

<tr className="cursor-pointer">
    <td>
        <Link to="patch" params={{patchId:patch.id}}>
            {patch.id}
        </Link>
    </td>
    <td>
        <Link to="patch" params={{patchId:patch.id}}>
            {patch.guid}
        </Link>
    </td>
    {/* etc */}
</tr>