1、先安装react-router-dom —> npm i react-router-dom
2、创建router.config.js文件
import React,{useState} from 'react'
import Home from './pages/home';
import Categroy from './pages/category/index'
import Recommend from './pages/recommend/index'
import Shopcar from './pages/shopcar/index'
import Mine from './pages/mine/index'
import Detail from './pages/detail/index'
import Error from './pages/error/index'
import List from './pages/list/index'
import {Route,Switch,Redirect} from 'react-router-dom'
const RouterComp = props =>{
const [routes] = useState([
{
id:1,
path:'/home',
component:Home
},
{
id:2,
path:'/categroy',
component:Categroy
},
{
id:3,
path:'/recommend',
component:Recommend
},
{
id:4,
path:'/shopcar',
component:Shopcar
},
{
id:5,
path:'/mine',
component:Mine
},
{
id:6,
path:'/list',
component:List
},
{
id:7,
path:'detail',
component:Detail
},
{
id:8,
path:'',
component:Error
}
])
function renderRoutes(){
return routes.map(item=><Route key = {item.id} path ={item.path} component={item.component} exact = {item.exact}/>)
}
return (
<Switch>
<Redirect from ='/' to = '/home' exact/>
{renderRoutes()}
</Switch>
)
}
export default RouterComp
3、导出RouterComp组件,并使用
import React, { Component } from 'react'
import Tab from '../components/tab';
import Tabbar from '../components/tabbar';
import './index.scss'
import RouterComp from '../router.config';
export default class Layout extends Component {
constructor(props) {
super(props)
this.state = {
tab_flag:true,
goback_flag:false
}
}
render() {
const {tab_flag,goback_flag} = this.state
return (
<div className='layout'>
{tab_flag && <Tab goback_flag={goback_flag}/>}
<RouterComp/>
<Tabbar/>
</div>
)
}
}
4、找到入口文件index.js
import {BrowserRouter as Router} from 'react-router-dom'
ReactDOM.render(
<Router>
<App />
</Router>
, document.getElementById('root'));
5、找到点击a标签,将其改成NavLink
import React, { useState } from 'react'
import './index.scss'
import{NavLink} from 'react-router-dom'
const Tabbar = props => {
const [Tabbars] = useState([
{
id: 1,
iconName: 'fa-home',
text: '首页',
path: '/home'
},
{
id: 2,
iconName: 'fa-reorder',
text: '分类',
path: '/category'
},
{
id: 3,
iconName: 'fa-shopping-bag',
text: '9.9包邮',
path: 'recommend'
},
{
id: 4,
iconName: 'fa-shopping-cart',
text: '购物车',
path: '/shopcar'
},
{
id: 5,
iconName: 'fa-user-circle',
text: '我的',
path: '/mine'
},
])
function renderItem() {
return Tabbars.map(item => {
return <li key={item.id}>
{}
<NavLink to = {item.path}>
<i className={'fa '+item.iconName}></i>
<span>{item.text}</span>
</NavLink>
</li>
})
}
return (
<footer>
<ul>
{renderItem()}
</ul>
</footer>
)
}
export default Tabbar