编程式导航: 通过js代码来实现页面跳转
案例:点击登录按钮,登录成功后,通过代码跳转到后台首页,如何实现?
答:
props.history.push("./home")
props.history.go(-1)
history:是react路由提供的,用来获取 浏览器历史记录的相关信息.
push(path):跳转到某个页面,参数path表示要跳转的路径
go(n):返回某个页面,参数n表示前进或后退页面数量(-1表示后退一页)
- import React from "react";
- import {createRoot} from 'react-dom/client';
- //导入路由的核心组件
- import {HashRouter, BrowserRouter as Router, Route, Link} from "react-router-dom"
-
- class App extends React.Component {
- render() {
- return (
- <Router>
- <h2>编程式导航apph2>
- <Link to="/login">去登录页面Link>
- <Route path="/login" component={Login}>Route>
- <Route path="/home" component={Home}>Route>
- Router>
- )
- }
- }
-
- class Login extends React.Component {
- fn = () => {
- this.props.history.push("./home")
- }
-
- render() {
- return (
- <div>
- <h2>这是登录页面h2>
- <button onClick={this.fn}>登录button>
- div>
- )
- }
- }
-
- const Home = (props) => {
- const back=()=>{
- //go(-1)表示返回上一个页面
- props.history.go(-1);
- }
- return(
-
- <div>
- <h2>我是后台首页h2>
- <button onClick={back}>返回登录页面button>
- div>
- )
- }
-
- createRoot(document.getElementById('root')).render(<App/>);
效果

点击链接 "去登录页面" → 展示 登录页面

点击 登录页面的 登录按钮 → 展示后台首页

点击后台页面的 返回按钮 → 返回登录页面
