针对react路由的讲解我这边会给出十个例子,这十个例子参考与react-router-dom官网。官网中的例子为了讲解方便会将一个例子中涉及的代码放在一个js文件中,没有按照企业项目规范放置代码,我这里会将代码按常规的写法重构,方便理解。
前言:
1、倘若读者对react-router-dom还是一个小白,我建议读者在遇到一些基础问题(例如:该组件什么意思、作用是什么,属性什么意思诸如此类)时可以点击参考这篇文档。
2、小编是默认你已经用脚手架搭建好了react的开发环境、安装好了react-router-dom依赖的基础上讲解的,倘若你还不会脚手架安装,可参考官网。
实现效果:
涉及知识点:
一般一个路由的至少会有三大组件,分别是BrowserRouter、Route、Link;
BrowserRouter:可以将其理解为一个容器,用来放Route、Link。
Route:可以理解为当前要展示的视图,会根据路由中不同的路径呈现不同展示。Route会有三大props,分别是location、history、match;其中match有包含params、isExact、path、url这些属性。
Link:申明了路由的路由,要跳转的地方,简单的可以理解为“要到哪去”。
App.js中配置的主路由如下:
import React, {Component} from 'react';
import {
BrowserRouter as Router,
Route,
Link
} from 'react-router-dom';
import Home from './home/Home';
import About from './about/About';
import Topics from './topics/Topics';
class App extends Component {
render() {
return (
<div>
<Router>
<div>
<ul>
<li><Link to='/'>首页</Link></li>
<li><Link to='/about'>关于</Link></li>
<li><Link to='/topics'>主题列表</Link></li>
</ul>
<Route exact path='/' component={Home} />
<Route path='/about' component={About} />
<Route path='/topics' component={Topics} />
</div>
</Router>
</div>
)
}
}
export default App;
Link根据写明了路由的跳转路径,类似于a标签,Route根据不同的路径展示不同的内容。
这个例子的难点主要在于Topics.js组件中,它有自己的路由,同时该路由用到了match这一props。倘若你要知道match是Route的props这一直知识点,该例子还是很好理解的。
再有就是{`${this.props.match.url}`}这是es6模版字符串的写法,会简化字符串拼接,例如{`${this.props.match.url}/rendering`}
中用反引号包裹,${}中是变量。
export default class Topics extends Component {
render() {
return (
<div>
<h1>主题列表</h1>
<ul>
<li>
<Link to={`${this.props.match.url}/rendering`}>
{`${this.props.match.path}`}
</Link>
</li>
<li>
<Link to={`${this.props.match.url}/components`}>
组件
</Link>
</li>
<li>
<Link to={`${this.props.match.url}/props-v-state`}>
属性 v 状态
</Link>
</li>
<Route path={`${this.props.match.url}/:topicId`} component={Topic} />
<Route exact path={this.props.match.url} render={() => (
<h3>请选择一个主题</h3>
)}/>
</ul>
</div>
)
}
}
注:一个Route有三种render方式,这个Topics.js分别用的render方式和component方式。这也是最长用的方式。还有一种是children。
子路由使用的Topic组件展示了Topics组件传下来的params。通过this.props.match.params.topicId可以获取到。
import React, {Component} from 'react';
export default class Topic extends Component{
render() {
return (
<div>
{`${this.props.match.params.topicId}`}
</div>
)
}
}
倘若你还不理解请参考我的github上的这个示例
https://github.com/guoqin721/react-router-dom1