1.下载依赖
npm i react-router-dom
2.配置文件 router/index.js
import { createBrowserRouter,Navigate } from'react-router-dom';
import main from '../pages/mian';
import home from '../pages/home/index';
const routes = [
{
path: '/',
Component: main,
children: [
// 重定向
{
path: '/',
element: <Navigate to="home" replace />
},
{
path: '/home',
Component: home
}
]
}
]
export default createBrowserRouter(routes)
3.创建文件 pages/mian.js
import React from "react";
import { Outlet } from "react-router-dom";
const main = () => {
return (
<div>
<h1>Welcome to my React App!</h1>
<p>This is the main component.</p>
{/* 显示子文件位置 */}
<Outlet />
</div>
);
}
export default main;
4.创建页面组件 pages/home/index.js
import React from 'react';
const home = () => {
return (
<div>
<h1>Home Page</h1>
<p>Welcome to the Home Page!</p>
</div>
);
}
export default home
5.在入口文件App.js导入router
import { RouterProvider } from 'react-router-dom';
import router from './router'
function App() {
return (
<div className='app'>
<RouterProvider router={router}></RouterProvider>
</div>
);
}
export default App;
6.使用方法
import { useLocation,useNavigate } from 'react-router-dom'
//获取路由信息
const action = useLocation()
//路由跳转
const navigate = useNavigate()
navigate('/home')