[英]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.