在React Router 4中单击材料ui表行时需要导航链接

Bha*_*asu 6 reactjs react-router

我正在使用反应路由器4和React Material UI,同时单击反应材料表行我可以通过使用onCellClick事件触发事件,但我需要在单击表行时导航另一个页面.

你能建议最好的办法吗?

<Table  onCellClick={()=> { alert("Table Row Clicked!! ")}} >

 <TableHeader displaySelectAll={false}
        adjustForCheckbox={false}>
        <TableRow>
          <TableHeaderColumn> First</TableHeaderColumn> 
          <TableHeaderColumn>Last</TableHeaderColumn>
        </TableRow>
 </TableHeader>
<TableBody displayRowCheckbox={false}>
        <TableRow>
          <TableRowColumn>Randal</TableRowColumn>
          <TableRowColumn>White</TableRowColumn>
        </TableRow>
 </TableBody>
</Table>
Run Code Online (Sandbox Code Playgroud)

Tsu*_*uni 5

一种可能的解决方案是使用react-router-dom 中的Link组件。您可以使用链接组件“扩展”表格行组件。如:

 <TableRow component={Link} to="/pathGoesHere">
      <TableRowColumn>Randal</TableRowColumn>
      <TableRowColumn>White</TableRowColumn>
 </TableRow>
Run Code Online (Sandbox Code Playgroud)

另一种可能的方法是在 react-router-dom 中使用withRouter HoC包装您的组件。这允许您将历史对象作为道具访问。这种方法将使您有更多的控制力和灵活性。

const TableView = ({ history }) => {
   return (
       <TableRow hover onClick={() => history.push("/pathGoesHere")}>
         <TableRowColumn>Randal</TableRowColumn>
         <TableRowColumn>White</TableRowColumn>
       </TableRow>
     )
}

export default withRouter(TableView)
Run Code Online (Sandbox Code Playgroud)

  • 当您希望用户能够通过右键单击“在新选项卡中打开链接”时,第一个解决方案是更好的选择。但是,使用打字稿时它不起作用。至少我无法让它发挥作用。 (4认同)