【发布时间】:2020-08-24 08:53:21
【问题描述】:
该表是来自Semantic UI 的表。
使行可点击的一种方法是添加Link from react-router-dom。
喜欢这里:
import React from 'react';
import { Table } from 'semantic-ui-react';
import { Link } from 'react-router-dom'; // used for Link
export default class GenericTable extends React.PureComponent {
constructor(props) {
super(props);
}
render() {
const {
headers,
emptyFirstHeader,
rows,
id,
entityName,
idList,
} = this.props;
return (
<Table id={id}>
<Table.Header>
<Table.Row>
<Table.HeaderCell />
</Table.Row>
</Table.Header>
<Table.Body>
{rows.map((row, rowIndex) => (
<Table.Row
key={idList && idList[rowIndex]}
as={Link} // this line makes the row clickable but also adds the errors
to={entityName && `/${entityName}/${idList[rows.indexOf(row)]}`}> // the location of the redirect
{row.cells.map((cell, cellIndex) => {
if (cell === undefined) {
return null;
}
return (
<Table.Cell
key={idList && `${idList[rowIndex]} ${headers[cellIndex]}`}>
{cell}
</Table.Cell>
);
})}
</Table.Row>
))}
</Table.Body>
</Table>
);
}
}
问题是它在开发者工具中返回错误:
index.js:1 Warning: validateDOMNesting(...): <td> cannot appear as a child of <a>.
in td (created by TableCell)
in TableCell (at GenericTable.js:193)
in a (created by LinkAnchor)
in LinkAnchor (created by Context.Consumer)
in Link (created by TableRow)
in TableRow (at GenericTable.js:143)
in tbody (created by TableBody)
in TableBody (at GenericTable.js:141)
in table (created by Table)
in Table (at GenericTable.js:105)
尝试通过将as={Link} 替换为onClick 并将其连接到单独的函数来解决此问题。该错误消息现在消失了,但是当单击一行时,它不会重定向到所需的页面。
我在函数内部添加了一个 console.log 来检查它是否被调用。
这是代码:
navigateTo = (entityName, idList, rows, row) => {
console.log('click: ', entityName, row); // the log works
return (
<Link to={entityName && `/${entityName}/${idList[rows.indexOf(row)]}`} />
);
};
...
<Table.Body>
{rows.map((row, rowIndex) => (
<Table.Row
key={idList && idList[rowIndex]}
onClick={() => {
this.navigateTo(entityName, idList, rows, row);
}}
to={entityName && `/${entityName}/${idList[rows.indexOf(row)]}`}> // the location of the redirect
{row.cells.map((cell, cellIndex) => {
if (cell === undefined) {
return null;
}
return (
<Table.Cell
key={idList && `${idList[rowIndex]} ${headers[cellIndex]}`}>
{cell}
</Table.Cell>
);
})}
</Table.Row>
))}
</Table.Body>
任何想法为什么不起作用以及应该如何修改?
【问题讨论】:
-
当用户点击行时你想做什么。重定向到另一条路线?
-
@ShubhamVerma 是的。从链接到路线
-
如果可能的话,您可以将此代码添加到代码和框。基本上你需要反应路由器的帮助才能在行点击时推送路由
-
@ShubhamVerma 不幸的是,它无法添加到沙箱中,我可以说的是,当它具有
as={Link}时,它会在单击一行但出现该错误时重定向到该页面(这也会影响CSS样式,不知道为什么),当它有onClick={() ... }时,它不再有那个错误但是当它被点击时它不会重定向。
标签: javascript reactjs react-router semantic-ui react-router-dom