我在 React 中使用 jQuery DataTable。 (我知道,在 React 中使用 jQuery 并不好,但它已经很久了,而且该插件中的许多功能自定义,我们没有在其他插件中获得)
使用 columns hook 我们可以在其中一个列中添加 anchor 链接(它工作正常但由于不使用 react router 页面刷新)
let columnConfig = [ ...ManyOtherColumns, { orderable: false, className: 'view-page-cell', "width": "35px", "defaultContent": "", "createdCell": function (td, cellData, rowData, row, col) { //Some custom logic here... let anchor = `<a class="view-page" title="${title}" href="${url}"> <img class="image" src="${viewIcon}" width="16" /> </a>`; ReactDOM.render(anchor, td ) } } ]
无法添加
Link
的react-router-dom
(使用版本“5.2.0”)(代码示例如下),出现类似Uncaught Error: Invariant failed: You should not use <Link> outside a <Router>
的错误let columnConfig = [ ...ManyOtherColumns, { orderable: false, className: 'view-page-cell', "width": "35px", "defaultContent": "", "createdCell": function (td, cellData, rowData, row, col) { // custom logic here.. ReactDOM.render(<Link to={url} isactive="true" className="view-page"><img src="${viewIcon}" /></Link>, td ) } } ]
DataTable初始化如下
wrapper.find('.data-table-grid').DataTable({ ...OtherConfig, columns: columnConfig });
更多信息请查看我的codepen:https://codepen.io/jsnaghera/pen/vYrwgQz
注意:在单元格和 useHistory
上使用点击事件不会完全满足我的要求,因为我需要用户可以右键单击并在新选项卡中打开页面的功能。
最佳答案
很抱歉,您将无法使用 react-router
在您的 jQuery 代码中。
"createdCell": function (td, cellData, rowData, row, col) {
// custom logic here..
ReactDOM.render(<Link to={url} isactive="true" className="view-page"><img src="${viewIcon}" /></Link>, td )
}
当您调用 ReactDOM.render
时在这里您正在创建一个完全独立的组件树。这Link
不会在Router
里面那在你的 App
里.
最简单的解决方案是使用标准 <a>
标签如<a href="/view-page">
. React-router 将处理加载该路径的正确内容。但是单击此链接将导致应用程序完全重新加载,而不是像使用 <Link>
那样在现有应用程序实例中导航。 .
您可以使用 react-router
只要您不使用额外的 ReactDOM.render
.
我想出了一个解决方案,你可以使用 <Link>
在创建表标记的代码中,而不是在 jQuery 中修改标记的地方。
我制作了一个返回 <td>
的组件:
const LinkedCell = ({ children }) => (
<td>
<Link to="/view-page">
<img src="https://cdn-icons-png.flaticon.com/512/5566/5566326.png" width="25" height="25" alt="" title="" className="img-small"/>
{children}
</Link>
</td>
)
然后在 return
中使用它你的App
:
<tbody>
<tr>
<LinkedCell>Tiger Nixon</LinkedCell>
<td>System Architect</td>
这消除了你的 columnDef
, 所以现在你只需要:
useEffect(()=>{
$('#example').DataTable();
},[])
关于jquery - react-router-dom 的链接在 DataTable createdCell Hook 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74743735/