使用create-react-app进行中后台开发(三、布局与路由结合)
1、将路由与页面布局结合起来,使得点击超链接即可跳转页面
参考官方教程:https://reactrouterdotcom.fly.dev/docs/en/v6/examples/basic
我们先将根目录下的App.js、App.css、AppTest.js删除
修改router.js
import { BrowserRouter, Routes, Route, Outlet, Link } from "react-router-dom"; import Home from '../pages/home/home'; import User from '../pages/user/user'; import Error from '../pages/error/error'; function Router(){ return( <BrowserRouter> <Routes> <Route path="/" element={<Layout />}> <Route path="user" element={<User/>}></Route> <Route path="home" element={<Home/>}></Route> <Route path="*" element={<Error/>}></Route> </Route> </Routes> </BrowserRouter> ); } function Layout() { return ( <div> {/* A "layout route" is a good place to put markup you want to share across all the pages on your site, like navigation. */} <nav> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/user">User</Link> </li> <li> <Link to="/error">Nothing Here</Link> </li> </ul> </nav> <hr /> {/* An <Outlet> renders whatever child route is currently active, so you can think about this <Outlet> as a placeholder for the child routes we defined above. */} <Outlet /> </div> ); } export default Router;
此时的页面结构:点击url时页面会进行跳转
2、将layout进行提取:提取到layout.js,然后在router.js中引入即可达到相同效果。
3、重写layout.js布局文件,改变成为中后台管理端样式:
import './layout.css'; import { Outlet, Link } from "react-router-dom"; import NavLogo from '../resources/images/logo192.png'; export default function AdminLayout(){ return( <section> <div className="right"> <div className="content"> <div className="ctop"> header </div> <div className="cmain"> <div className="cccc"> 内容 <Outlet /> </div> </div> </div> </div> <div className="left"> <div className="title"> <img src={NavLogo}></img> </div> <div className="nav"> nav <div > <Link to="/user">User</Link> </div> <div > <Link to="/home">Home</Link> </div> </div> </div> </section> ); }
同目录下layout.css文件为:
*{ margin:0; padding: 0; } section{ min-width: 400px; background: #eee; } .right,.left{ float: left; height:100%; min-height: 200px; } .left{ width: 230px; margin-left: -100%; background: lightblue; } .right{ width:100%; background: lightgreen; } .content{ margin:0 0 0 230px; } .title,.ctop{ height:50px; background: #113355; } .nav,.cmain{ position: absolute; top:50px; bottom:0; background: #113355; } .nav{ width: 230px; } .ctop{ background: #113355; } .cmain{ width:100%; background: white; margin-left:-230px; overflow: auto; } .cccc{ padding-left: 230px; height:900px; } /*以下为滚动条样式*/ ::-webkit-scrollbar { width: 5px; } ::-webkit-scrollbar-track { background-color: #bee1eb; } ::-webkit-scrollbar-thumb { background-color: #00aff0; border-radius: 3px; } ::-webkit-scrollbar-thumb:hover { background-color: #9c3 } ::-webkit-scrollbar-thumb:active { background-color: #00aff0 }
同时新目录存放我们的图片资源,最终得到目录:
此时整个页面展示为:
点击左侧nav导航,内容模块展示对应页面的文字。最后按照我们要的样式对文件进行调整即可