React(脚手架)——create-react-app撸api
2019-03-12 本文已影响0人
感觉不错哦
路由嵌套相当于vue的子路由,路由套路由
首先初始化布局
![](https://img.haomeiwen.com/i14714949/27054941cc4eb30f.png)
![](https://img.haomeiwen.com/i14714949/64982148925d848a.png)
![](https://img.haomeiwen.com/i14714949/4a008b7da041ee37.png)
我自己简单写了一点css,编辑一下user组件
import React, { Component } from 'react';
class User extends Component {
constructor(props) {
super(props);
this.state = { };
}
render() {
return (
<div className="user">
<div className="content">
<div className="left">
左侧
</div>
<div className="right">
右侧
</div>
</div>
</div>
);
}
}
export default User;
然后加点css
.content{
width: 100%;
height: 500px;
display: flex;
}
.content .left{
width: 200px;
height: 500px;
background: #eee
}
.content .right{
flex:1;
height: 498px;
border:1px solid #333
}
![](https://img.haomeiwen.com/i14714949/3ef0f696aaf013f6.png)
OK,大致布局就这样,最终效果就是在左侧编辑一些链接,通过这个链接在有边框显示其他不变
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Link } from "react-router-dom"
import UserInfo from './User/Userinfo'
import Main from './User/Main'
class User extends Component {
constructor(props) {
super(props);
this.state = { };
}
render() {
return (
<div className="user">
<div className="content">
<div className="left">
<Link to="/user/">个人中心</Link>
<Link to="/user/main">用户信息</Link>
</div>
<div className="right">
<Route path="/user/" exact component={UserInfo}/>
<Route path="/user/main" component={Main}/>
</div>
</div>
</div>
);
}
}
export default User;
![](https://img.haomeiwen.com/i14714949/9980c48b784dfc46.png)
这里是嵌套路由显示的组件,那么使用方法也是很简单,在需要显示的div中插入Route标签,配置路由的时候需要注意的就是user是当前组件的根路由
![](https://img.haomeiwen.com/i14714949/5b470deace7abd86.png)
当然如果后面没跟地址,自然的就是跟APP.js中的配置一个道理,默认点击User组件的时候显示个人中心,那么Link的Link自然是跟path相同
![](https://img.haomeiwen.com/i14714949/ad61ff248f833a62.png)
这样当点击用户组件的时候默认显示个人中心
那官方文档中是使用了动态获取父级路由url配置
${this.props.match.url}
![](https://img.haomeiwen.com/i14714949/817b934f14ffe43c.png)
效果是一样的!!