javascript - 使用 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)
在中添加了一个 onClick 函数
<tr>
和一个 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")
我没有通过user.id
,clickRow
因为出于某种奇怪的原因,它会在页面加载时自动触发它,所以我试图将其删除。尚未调查,但现在将使用此解决方案。
解决方案
放置一个 onClick 事件
<tr key={index} onClick={this.handleOnClick(user.id)}>
在 handleOnClick 中,使用 Redirect 链接到另一个页面,您可能还需要将 props 传递给 Redirect。
handleOnClick = (userid) => {
return <Redirect
to={{
pathname: "/profile",
foo: userid
}}
/>
}
推荐阅读
- mongodb - mongorestore 未捕获的异常:语法错误
- css - 如何正确引用 CSS?
- winapi - CancelIo 并不代表实际取消的 I/O
- reactjs - Python 服务器和 React Native 客户端之间的 AES 加密
- python - Pandas:基于多个子字符串值进行过滤
- python - 在 Python DataFrame 中创建聚合另一列的新列
- python - Python中两个远程服务器之间的scp
- autohotkey - AutoHotkey - 将热键发送到嵌套文件夹
- javascript - 如何使按钮在幻灯片上显示随机图像
- apache - .htacess 在一行上指定特定文件