[英]Making entire table row clickable using React Router Link
我对 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组件将替换为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 使其工作
我包括来自 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
因为出于某种奇怪的原因,它会在页面加载时自动触发它,所以我试图将其删除。 尚未调查,但现在可以使用此解决方案。
放置一个 onClick 事件
<tr key={index} onClick={this.handleOnClick(user.id)}>
在 handleOnClick 中,使用 Redirect 链接到另一个页面,您也可能需要将 props 传递给 Redirect。
handleOnClick = (userid) => { return <Redirect to={{ pathname: "/profile", foo: userid }} /> }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.