react默认路由嵌套子路由
程序员文章站
2024-02-13 20:37:46
...
import React from 'react'
import { Router, Redirect,Route, IndexRoute,browserHistory,hashHistory } from 'react-router'
import App from '../containers/App'
import Home from '../containers/Home'
import Phone from '../containers/phone/phone'
import Ditu from '../containers/Ditu/Ditu'
import Anli from '../containers/Anli/Anli'
import HomeIndex from '../containers/homeIndex/HomeIndex'
import List from '../containers/List'
import Detail from '../containers/Detail'
import About from '../containers/about/About'
import News from '../containers/news/News'
import Team from '../containers/Team/Team'
import NotFound from '../containers/NotFound'
class RouteMap extends React.Component {
render() {
return (
<Router history={browserHistory}>
<Redirect from="/" to="/HomeIndex" />
<Route path='/' component={App}>
<Route path='/HomeIndex' component={Home}>
<IndexRoute component={HomeIndex}/>
<Route path='/Home/About' component={About}/>
<Route path='/Home/News' component={News}/>
<Route path='/Home/Team' component={Team}/>
</Route>
<Route path='/list' component={List}/>
<Route path='/Phone' component={Phone}>
</Route>
<Route path='/Ditu' component={Ditu}/>
<Route path='/Anli' component={Anli}/>
<Route path='/detail/:id' component={Detail}/>
<Route path="*" component={NotFound}/>
</Route>
</Router>
)
}
}
export default RouteMap
总入口路由:
<div className="footer borderTop">
<Link to="/HomeIndex" activeClassName="routerActive" className="footerRouter">
<span className="bar1"></span>
首页
</Link>
<Link to="/Phone" activeClassName="routerActive" className="footerRouter">
<span className="bar2"></span>
电话
</Link>
<Link to="/Ditu" activeClassName="routerActive" className="footerRouter">
<span className="bar3"></span>
地图
</Link>
<Link to="/Anli" activeClassName="routerActive" className="footerRouter">
<span className="bar4"></span>
案例
</Link>
</div>
首页子路由:
import React from 'react'
import { Link,IndexLink } from 'react-router'
import { browserHistory } from 'react-router'
import Banner from '../../contents/banner/Banner'
class HomeIndex extends React.Component {
render() {
return (
<div className="content">
<Banner/>
<div className="navUl">
<Link to="/Home/About" className="navList">
<span className="bar1"></span>
关于我们
</Link>
<Link to="/Home/News" className="navList">
<span className="bar2"></span>
家装新闻
</Link>
<Link to="/Anli" className="navList">
<span className="bar3"></span>
案例展示
</Link>
<Link to="/Home/Team" className="navList">
<span className="bar4"></span>
设计团队
</Link>
</div>
</div>
)
}
}
export default HomeIndex
home文件:
import React from 'react'
import { browserHistory } from 'react-router'
class Home extends React.Component {
render() {
return (
<div>
{this.props.children}
</div>
)
}
}
export default Home
原理就是让home父组件作为一个容器,在其中一个子页面完成跳转
IndexRoute使用这个之后如果想在默认的路由下面嵌套子路由,会发现点击跳转后默认的路由失去了active状态,所以现在不使用这个了。直接利用react的路由重定向,将默认地址指向
需要展示的首页。