首页 > 解决方案 > 使用 React Router Link 使整个表格行可点击

问题描述

我对 React 还很陌生。我有一个名为Content的组件,它用作另外两个名为ListProfile的组件的容器。

class Content extends Component{
  <HashRouter>
    <Route exact path="/list">
       <List *props are entered here*/>
     </Route>
     <Route exact path="/profile">
        <Profile foo = {this.foo} *props are entered here*/>
     </Route>
  </HashRouter>
}

List中,我有一张从该州映射出来的用户表。当我单击链接时,函数foo获取用户 ID 并将其传递给ProfileList组件将替换为Profile组件,显示所选用户配置文件

<table>
 <thead>
  <tr >
    <th>User</th>
    <th>Link to profile</th>
  </tr>
 </thead>

 <tbody>
  {this.state.users.map((user, index) =>
   <tr key={index}>
     <td>{user.name}</td>
     <td><Link to="/profile" onClick={() => this.props.foo(user.id)}</Link></td>
   </tr>
   )}
 </tbody>
</table>

现在点击里面的链接<td>显然是可行的,但我想让整行看起来像一个可点击的<Link>

我尝试将onClick函数绑定到,<tr>但我不知道如何使它像<Link>将组件替换为Profile

编辑:根据 Jacob Smit 的评论,我设法使用 withRouter 使其工作

  1. 我包含了来自 react-router-dom 的 withRouter

    export default withRouter(List)

  2. 在中添加了一个 onClick 函数<tr>和一个 data-value 属性

    <tr key={index} onClick={this.clickRow} data-value{user.id}>

  3. 在 clickRow() 函数中

    this.props.foo(event.currentTarget.getAttribute("data-value"); this.props.history.push("/profile")

我没有通过user.idclickRow因为出于某种奇怪的原因,它会在页面加载时自动触发它,所以我试图将其删除。尚未调查,但现在将使用此解决方案。

标签: javascriptreactjsreact-router

解决方案


  1. 放置一个 onClick 事件

    <tr key={index} onClick={this.handleOnClick(user.id)}>

  2. 在 handleOnClick 中,使用 Redirect 链接到另一个页面,您可能还需要将 props 传递给 Redirect。

handleOnClick = (userid) => {
      return <Redirect
      to={{
        pathname: "/profile",
        foo: userid
        
      }}
    />
    }


推荐阅读