【发布时间】:2021-02-02 20:00:05
【问题描述】:
我对 React 还很陌生。 我有一个名为 Content 的组件,它用作另外两个名为 List 和 Profile 的组件的容器。
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 并将其传递给 Profile,List 组件将替换为 个人资料 组件,显示选定的用户个人资料
<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 使其工作
-
我从 react-router-dom 中包含了 withRouter
export default withRouter(List) -
在
<tr>中添加了一个onClick函数和一个data-value属性<tr key={index} onClick={this.clickRow} data-value{user.id}> -
在 clickRow() 函数中
this.props.foo(event.currentTarget.getAttribute("data-value"); this.props.history.push("/profile")
我没有在clickRow 中传递user.id,因为出于某种奇怪的原因,它会在页面加载时自动触发它,所以我试图将其删除。尚未调查,但现在可以使用此解决方案。
【问题讨论】:
-
由于您使用的是类组件,您可以使用
withRouter通过道具将history推送到您的组件上。然后您可以使用history.push(/* URL HERE */)来制作申请路线。如果您使用任何功能组件,您可以使用钩子useHistory而不是withRouterHOC。 -
这成功了!谢谢!
标签: javascript reactjs react-router