react点击事件跳转到详情页面
时间: 2023-05-29 07:06:56 浏览: 221
在React中,你可以使用React Router来实现页面之间的跳转。
首先,在你的App.js或者其他主要组件中,引入React Router:
```jsx
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
```
然后,在Router组件中,使用Switch和Route来定义你的路由:
```jsx
<Router>
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/details/:id" component={Details} />
</Switch>
</Router>
```
在上面的代码中,我们定义了两个路由:一个是根路由,对应到Home组件,另一个是/details/:id,对应到Details组件,其中:id是一个参数,用来传递详情页面的ID。
接下来,在你的点击事件处理函数中,使用React Router的history对象来跳转到详情页面:
```jsx
import { useHistory } from 'react-router-dom';
function handleClick(id) {
const history = useHistory();
history.push(`/details/${id}`);
}
```
在上面的代码中,我们使用useHistory hook来获取history对象,然后使用push方法来跳转到指定的路由。
最后,在Details组件中,可以使用useParams hook来获取路由参数:
```jsx
import { useParams } from 'react-router-dom';
function Details() {
const { id } = useParams();
return (
<div>
<h1>Details Page</h1>
<p>ID: {id}</p>
</div>
);
}
```
在上面的代码中,我们使用useParams hook来获取路由参数中的id值,然后在页面中显示出来。
这样,当你在页面中点击某个元素时,就可以调用handleClick函数来跳转到详情页面了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)