一、路由模块
在React项目中 若要实现页面的跳转 需使用路由
而react-router-dom正是React推荐的常用路由模块
安装
npm install react-router-dom
按需导入react-router-dom路由模块
HashRouter是路由的根容器 所有和路由相关的东西都要包裹在HashRouter内部 且一个网站只需要使用一次HashRouter
Router是路由规则(rules) 其上有两个重要属性:path和component
Link表示路由链接 类似于Vue中的<router-link>
import {HashRouter,Route,Link} from 'react-router-dom'
使用
App.jsx:
import Index from '@/components/Index'
import Type from '@/components/Type'
import About from '@/components/About'
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {}
}
render() {
// 当使用<HashRouter>将根组件的元素包裹起来后 网站即启动路由
// 在<HashRouter>内部只能有唯一的根标签
return <HashRouter>
<div>
<h1>App</h1>
<hr/>
{/* 可以点击的链接 默认在页面上渲染成a标签 */}
<Link to="/index">首页</Link>
<Link to="/type">分类</Link>
<Link to="/about">关于</Link>
<hr/>
{/* <Route>就是路由规则 path为要匹配的路由 component为要展示的组件 */}
{/* 在Vue中有专门的router-view路由标签用于放置匹配到的路由组件 而在react-router-dom中并没有类似标签 而是直接将<Route>标签作为占位符了 */}
<Route path="/index" component={Index}></Route>
<Route path="/type" component={Type}></Route>
<Route path="/about" component={About}></Route>
</div>
</HashRouter>
}
}
当组件套上了<HashRouter>
标签之后 页面的URL后面就会自动带上/#
以供路由跳转
<Link to="/index">首页</Link>
就是可点击的a标签 当点击之后 页面就会跳转到to属性配置的目标页
<Route path="/index" component={Index}></Route>
在页面上负责渲染对应页面上的内容 同时 也承担着匹配路由规则的任务 身兼两职
path属性代表要匹配的路由路径 而component属性代表所要渲染的组件(前提是必须先在页面中导入该注解)
二、路由参数
react-router-dom在默认情况下 路由规则是模糊匹配的
即 路由若可部分模糊匹配成功 即展示对应组件
若想让路由规则精确匹配 可为<Route>添加exact
属性以启用精确模式
react-router-dom和vue-router一样 也是用冒号:
来为路由添加匹配参数
像这样:
<Route path="/type/:typeName/:id" component={Type} exact></Route>
这样即可成功匹配了:
<Link to="/type/car/12">分类</Link>
获取路由参数
在组件中 通过this.props.match.params.参数名
来获取URL上的路由参数
像这样:
import React from 'react';
export default class Type extends React.Component {
constructor(props) {
super(props);
this.state = {}
}
render() {
console.log(this)
console.log(this.props.match.params.typeName)
console.log(this.props.match.params.id)
return <div>
{this.props.match.params.typeName} - {this.props.match.params.id}
</div>
}
}
也可写在构造器中
import React from 'react';
export default class Type extends React.Component {
constructor(props) {
super(props);
this.state = {
routeParams:props.match.params
}
}
render() {
return <div>
Movie - {this.state.routeParams.typeName} - {this.state.routeParams.id}
</div>
}
}