【问题标题】:Making entire table row clickable using React Router Link使用 React Router Link 使整个表格行可点击
【发布时间】:2021-02-02 20:00:05
【问题描述】:

我对 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 组件将替换为 个人资料 组件,显示选定的用户个人资料

<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>

现在点击 &lt;td&gt; 内的链接显然可以,但我想让整行看起来像可点击的 &lt;Link&gt;

我尝试将 onClick 函数绑定到 &lt;tr&gt;,但我不知道如何使它像 &lt;Link&gt; 一样将组件替换为 Profile

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

  1. 我从 react-router-dom 中包含了 withRouter

    export default withRouter(List)

  2. &lt;tr&gt;中添加了一个onClick函数和一个data-value属性

    &lt;tr key={index} onClick={this.clickRow} data-value{user.id}&gt;

  3. 在 clickRow() 函数中

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

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

【问题讨论】:

  • 由于您使用的是类组件,您可以使用withRouter 通过道具将history 推送到您的组件上。然后您可以使用history.push(/* URL HERE */) 来制作申请路线。如果您使用任何功能组件,您可以使用钩子useHistory 而不是withRouter HOC。
  • 这成功了!谢谢!

标签: javascript reactjs react-router


【解决方案1】:
  1. 上放置一个 onClick 事件

    &lt;tr key={index} onClick={this.handleOnClick(user.id)}&gt;

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

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

【讨论】:

    猜你喜欢
    • 2016-06-04
    • 2019-10-20
    • 2020-10-07
    • 2021-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    相关资源
    最近更新 更多