react跳转返回到原来位置
时间: 2023-08-18 16:06:18 浏览: 47
如果你想要在 React 应用中实现跳转并返回到原来位置,可以使用 React Router 库提供的 `history` 对象。具体步骤如下:
1. 在需要实现跳转的组件中引入 `history` 对象:
```javascript
import { useHistory } from "react-router-dom";
```
2. 获取 `history` 对象:
```javascript
const history = useHistory();
```
3. 在需要跳转的地方,使用 `history.push()` 方法跳转到目标页面:
```javascript
history.push("/target-page");
```
4. 在目标页面中,使用 `history.goBack()` 方法返回到原来的位置:
```javascript
import { useHistory } from "react-router-dom";
const history = useHistory();
function TargetPage() {
return (
<div>
<button onClick={() => history.goBack()}>返回</button>
</div>
);
}
```
这样就可以实现跳转并返回到原来位置的功能。
相关问题
react 路由跳转方法
在React中,有几种方式可以实现页面跳转。其中一种方式是使用react-router-dom中的Link组件来实现页面跳转。你可以在按钮或其他组件上使用Link组件,通过to属性指定目标路径,并可以传递数据作为state属性。例如:
```
import { Link } from 'react-router-dom';
...
<Link to={{ pathname: '/path/newpath', state: { data1: {}, data2: [] } }}>
<Button>点击跳转</Button>
</Link>
```
另一种方式是使用react-router-redux中的push方法进行页面跳转。你可以通过dispatch来发送push或replace方法,其中push方法可以跳转到指定路径,replace方法可以替换历史记录中的当前位置。具体使用时可以像下面这样:
```
import { push, replace } from 'react-router-redux';
...
let param1 = {};
dispatch(push("/path/newpath", param1));
dispatch(replace("/path/newpath", param1));
```
还有一种方式是使用RouteComponentProps中的history对象进行页面回退。你可以通过history对象的go、goForward和goBack方法来向前或向后移动历史记录中的位置。具体使用时可以像下面这样:
```
import { RouteComponentProps } from 'react-router-dom';
interface MyComponentProps extends RouteComponentProps {}
...
const MyComponent: React.FC<MyComponentProps> = ({ history }) => {
const handleGoBack = () => {
history.goBack();
};
return (
<div>
<button onClick={handleGoBack}>返回</button>
</div>
);
};
```
以上是React中几种常见的路由跳转方法。你可以根据实际需求选择使用其中的一种方式来实现页面跳转。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [react路由跳转](https://blog.csdn.net/qq_46503396/article/details/123813712)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
react移动端返回按钮返回指定路由
在 移动端应用中,可以使用 react-router-dom 库来实现路由的跳转和管理。如果想要返回到指定的路由,可以使用 `history` 对象的 `push()` 和 `goBack()` 方法。具体实现步骤如下:
1. 在需要返回的组件中引入 `useHistory` 钩子函数,获取 `history` 对象:
```javascript
import { useHistory } from 'react-router-dom';
function MyComponent() {
const history = useHistory();
// ...
}
```
2. 在需要返回的地方调用 `goBack()` 方法返回上一级路由:
```javascript
history.goBack();
```
3. 如果要返回到指定的路由,可以先使用 `push()` 方法跳转到该路由,再调用 `goBack()` 方法返回指定路由:
```javascript
history.push('/my/route'); // 跳转到指定路由
history.goBack(); // 返回到指定路由
```
注意:在使用 `push()` 方法跳转到指定路由时,需要保证该路由已经存在于路由栈中,否则无法返回到该路由。