使用react-router-dom(version6)实现单击导航栏页面更新功能。
先看一下demo效果:
首先使用脚手架生成一个react项目:
npx create-react-app app
进入到项目目录:
cd app
执行启动命令:
npm run start
然后再在src目录新建一个router.js,此文件是存放路由页面的。
import home from './views/home.js'
import one from './views/one.js'
import two from './views/two.js'
const routers = [
{
title: 'home',
path: '/',
component: home,
name: 'home'
},
{
title: 'one',
path: '/one',
component: one,
name: '页面一'
},
{
title: 'two',
path: '/two',
component: two,
name: '页面二'
}
]
export default routers
然后在views文件夹下面新增三个子页面
home页
function home() {
return (
<>
<div>
home
</div>
</>
);
}
export default home;
one页面
function one() {
return (
<div>
one
</div>
);
}
export default one;
two页
function two() {
return (
<div>
two
</div>
);
}
export default two;
修改APP.js页面:
import './App.css';
import {
BrowserRouter as Router,Routes,Route,Link} from "react-router-dom";
import routers from "./router";
function App() {
return (
<>
<header className='Header'>welcome</header>
<div className="App">
<Router>
<div className='Aside'>
{
routers.map((item, index) => {
return (
(
<Link to={item.path} key={index}>{item.name}</Link>
)
)
})
}
</div>
<div className='Content'>
<Routes>
{
routers.map((item, index) => {
return (
(
<Route
key={index}
path={item.path}
element={<item.component />}
/>
)
)
})
}
</Routes>
</div>
</Router>
</div>
</>
);
}
export default App;
Link 组件用于渲染导航栏,
Routes组件 用于展示子页面区域,会根据link的path去匹配。
css
.App {
text-align: left;
display: flex;
width: 100vw;
height: calc(100vh - 60px);
flex: auto;
box-sizing: border-box;
}
.App-logo {
height: 40vmin;
pointer-events: none;
}
@media (prefers-reduced-motion: no-preference) {
.App-logo {
animation: App-logo-spin infinite 20s linear;
}
}
.App-header {
background-color: white;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.App-link {
color: #61dafb;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
.Header {
height: 60px;
background-color: #0e49b3;
line-height: 60px;
padding-left: 24px;
color: white;
font-style: italic;
font-size: 24px;
}
.Aside {
padding: 8px;
width: 200px;
background-color: cornflowerblue;
}
.Aside > a {
display: block;
color: white;
}
.Content {
padding: 8px;
flex-grow: 1;
}