React-Router-dom@6模块化使用
!!!多的不说,先看效果,再上代码
React-router@6路由演示
1、基本介绍
本演示案例使用vite构建的react项目
1-1、使用vite快速构建React项目
npm create vite@latest React-demo
然后选择React回车
打开项目需要npm i
安装一下依赖
运行项目npm run dev
2、在router/index.jsx中
import Home from "../components/Home.jsx"; import About from "../components/About.jsx"; import {Navigate} from "react-router-dom"; import Vue from "../components/Vue.jsx"; import ReactCorse from "../components/ReactCorse.jsx"; const Router = [ { path:'/', element: <Navigate to={'/home'}/> }, { path: '/home', element:<Home/> }, /** * 用于重定向 * 默认显示about下的vue组件 * */ { path: '/about', element: <Navigate to={'/about/vue'}/>, }, { path: '/about', element: <About/>, children:[ { path:'vue', element: <Vue/> }, { path: 'react', element: <ReactCorse/> } ] } ] export default Router;
3、main.jsx中
import React from 'react' import ReactDOM from 'react-dom/client' import App from './App.jsx' import {BrowserRouter} from "react-router-dom"; ReactDOM.createRoot(document.getElementById('root')).render( <BrowserRouter> <App /> </BrowserRouter>, )
4、App,jsx中
import React from 'react'; import {useRoutes} from "react-router-dom"; import Router from "./route/index.jsx"; const App = () => { return ( <> {useRoutes(Router)} </> ); }; export default App;
5、components/Home.jsx组件中
import React from 'react'; import {useNavigate} from "react-router-dom"; const Home = () => { const navigate = useNavigate() return ( <div className={'Home'}> <h2>Home</h2> <button onClick={()=>navigate('/about')}>去about</button> </div> ); }; export default Home;
6、components/About.jsx组件中
import React from 'react'; import {NavLink, Outlet, useNavigate} from "react-router-dom"; import '../assets/css/About.scss' const About = () => { const navigate = useNavigate() return ( <div> <h2>About</h2> <button onClick={()=>navigate('/')} >返回</button> <div> <NavLink to={'vue'}>Vue</NavLink> <NavLink to={'react'}>React</NavLink> </div> {/*about下的二级路由视图*/} <Outlet/> </div> ); }; export default About;
7、components/VueCourse.jsx组件中
import React from 'react'; const VueCourse = () => { return ( <div> <h3>Vue课程</h3> </div> ); }; export default VueCourse;
8、components/ReactCourse.jsx组件中
import React from 'react'; const ReactCourse = () => { return ( <div> <h3>React课程</h3> </div> ); }; export default ReactCourse;