React路由跳转
引入包
import { HashRouter, Route, Routes } from 'react-router-dom';
App.js中配置路由信息
import React from 'react'
import Login from './views/login/Login.jsx'
import Register from './views/register/Register.jsx'
import Layout from './views/layout/Layout'
import { HashRouter, Route, Routes } from 'react-router-dom';
function App() {
return (
<HashRouter>
{/* routes线路匹配容器,所有组件都要放置才这里 */}
<Routes>
{/* 默认登录 */}
<Route path='/' exact element={<Login />}></Route>
{/* 登录 */}
<Route path='/Login' element={<Login />}></Route>
{/* 注册 */}
<Route path='/Register' element={<Register />}></Route>
<Route path='/Layout' element={<Layout />}></Route>
</Routes>
</HashRouter>
);
}
export default App;
点击按钮跳转
//如有引入Link
import { Link} from 'react-router-dom';
<Link to="/Register">前往注册</Link>
函数中使用
在 React Router v6 中,useHistory 已被替换为 useNavigate
//引入包
import { useNavigate } from 'react-router-dom';
const navigate = useNavigate();
//调用navigate 传入路由地址即可
navigate('/Layout');