1.引入(此文章针对5.x版本)
import { BrowserRouter as Router, Switch, Route,HashRouter,Link } from 'react-router-dom'
<Router>
<Switch>
<Route path='/' exact component={Routerone}></Route>
<Route path='/two' component={RouterTwo}></Route>
<RouterTwo path="/two">
<Route path='/two/one' component={ChildOne}></Route>
<Route path='/two/two' component={ChildTwo}></Route>
<Route path='/two/three' component={ChildThree}></Route>
</RouterTwo>
</Switch>
// {renderRoutes(routes)} //批量管理路由插件
嵌套子路由显示到页面中的
{this.props.child} 位置上 需要在父组件页面render添加此代码
</Router>
2.插件react-router-config
创建router 文件夹 用来管理所有路由创建router.jsx
const Home = () => {
return <div>这是home</div>;
};
const Group = () => {
return <div>这是Group</div>;
};
const About = () => {
return <div>这是about</div>;
};
const routes = [
{
path: "/",
component: Home,
exact: true,
},
{
path: "/group",
component: Group,
},
{
path: "/about",
component: About,
},
{
path: "/two",
component: RouterTwo,
routes: [
{
path: "/two/one",
component: ChildOne,
routes: [
{
path: "/two/one/tone",
component: ChildTone,
}
]
},
{
path: "/two/two",
component: ChildTwo,
},
{
path: "/two/three",
component: ChildThree,
}
]
},
];
export default routes;
在index.jsx或者app.jsx中引入
import { renderRoutes } from 'react-router-config'
import routes from './router'
<Router>
{renderRoutes(routes )}
</Router>
关于嵌套路由
需要把前面的{this.props.children}
替换成
{this.state.route.routes}
类组件如下
constructor(props) {
super(props)
this.state = {
route: props.route
}
}
render() {
console.log((this.state.route) //如果不显示子组件 打印一下看看结构 可能不是routes
return (
<div onClick={this.ttt}>我是第一个子组件
{renderRoutes(this.state.route.routes)}
</div>
)
}
如果组件中不能使用this.props.history.push();
如果是5.x版本的react-router
将组件用withRouter包裹后再暴露出去
import { withRouter } from 'react-router-dom'
export default withRouter(RouterTwo)