npm i -S react-router-dom
Link/NavLink组件:用于指定导航链接(a标签)
to属性:会被编译成 a标签的href属性 to='/main' || to='{{pathname='/main'}}'
activeClassName属性:指定样式名
Link 不会显示按钮的高亮显示, NavLink 来替代它
最终Link会编译成a标签,
Route组件:指定路由展示组件相关信息(组件渲染)
path属性:路由规则,这里需要跟Link组件里面to属性的值一致
exact属性:严格匹配, 为true
是表示严格匹配,为false
时为正常匹配。
component属性:展示的组件
render属性:用于页面组件级别的权限管理
步骤一:定义路由模式
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import store from './store'
import {HashRouter ar Router} from 'react-router-dom'
ReactDom.render(
<Provider store={store}>
<Router>
<App/>
</Router>
<Provider>,
document.getElementById('root')
)
步骤二:组件内渲染路由 + 路由声明式导航
import React, { Component } from 'react'
import { Route, Link } from 'react-router-dom'
<!-- 导入渲染组件 -->
const Home = () => (<div>Home</div>)
const About = () => (<div>About</div>)
const DashBord = () => (<div>DashBord</div>)
class App extends Component {
render() {
return (
<>
<ul>
{/* 声明导航*/ }
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="{{pathname:'/dashbord'}}">DashBord</Link></li>
</ul>
{/*
path:可访问的url路径
component:匹配成功的渲染的组件
exact:严格匹配模式
Route组件中匹配成功,渲染会自动在this.props中添加路由导航相关属性方法
*/ }
<Route path="/" exact component={Home}></Route>
<Route path="/about" component={About}></Route>
<Route path="/dashbord" component={DashBord}></Route>
</>
);
}
}
export default App;
在Route定义渲染组件时给定动态绑定的参数
params:在路由目标页面中
动态路由定义:<Route path='/detail/:id' component={Detail}>
传递:<NavLink to='/detail/2'>
获取:this.props.match.params
query:通过地址栏中的 ?key=value&key=value,
传递:<NavLink to='/detail?name=cc'>
获取:this.props.location.search
备注:获取到的search是urlencoded编码字符串,需要借助querystring解析
state:隐式转参,用于数据的收集
传递:<NavLink to='{{pathname:/detail?name=cc,state:{age:20}}}'>
获取:this.props.location.state
作用:埋点---收集数据统计
import { Route,Switch } from 'react-router-dom'
<div>
<div>
<ul>
<li>
<Link to="/Guide/ContactUs">ContactUs</Link>
</li>
</ul>
</div>
<Switch>
<Route path="/Guide/ContactUs" component={ ContactUs } ></Route>
<Route path="/Guide/ContactUs" component={ ContactUs } ></Route>
<Redirect from="/" to="/public"></Redirect>
</Switch>
</div>
1、component
<Route path='/home' component={home}/>
<Route path='/home' component={()=><home/>} />
<Route path='/home' component={()=>{
return <Home count={this.state.count}/>
}}/>
2、render<Route path="/home" render={props=><Home />} />
<Route path='/home' render={()=>{
if(this.state.count==1){
return <Home1 count={this.state.count}/>
}else{
retutn <Home2/>
}
}}/>
3、children
组件对象方式:必须匹配到path的路由规则才渲染和render与component一样<Route path="/about" children={<About />} />
函数方式:不管是否和path匹配都渲染
match为null表示当前路由规则和path不匹配,如果为对象则匹配成功
<Route path="/about" children={match=>{
if(match){
return <div>children渲染</div>
}
}} />
3种渲染区别总结
比较一
比较二
比较三
借助this.prosp.history
对象上的API对操作路由跳转、前进、后退
**注:**默认组件中没有this.props.history方法,需要通过withRouter高阶组件(装饰器)来进行包裹,才能得到。
this.props.history.push(path)
或
this.props.history.push({
pathname:'',
search:'',
state:{}
})
路由监听
在App.jsx组件中可以添加路由监听
constructor(props) {
super(props);
this.props.history.listen(route=>console.log(route))
}
作用:把不是通过路由切换过来的组件中,将react-router 的 history、location、match 三个对象传入props对象上
import { withRouter} from 'react-router-dom'
执行一下withRouter
export default withRouter(Cmp)`import React, { Component } from 'react'
import {withRouter} from 'react-router-dom'
class Header extends Component {
// 回退
back = () => {
this.props.history.goBack()
}
// 前进
forward = () => {
this.props.history.goForward()
}
/// go
go = () => {
this.props.history.go(2)
}
render() {
// console.log('一般组件',this.props)
return (
<div className="page-header">
<h2>React Router Demo</h2>
<button onClick={this.back}>回退</button>
<button onClick={this.forward}>前进</button>
<button onClick={this.go}>go</button>
</div>
)
}
}
export default withRouter(Header)
import React from 'react'
import {withRouter,Route} from 'react-router-dom'
const MyLink = props=>{
const gourl=()=>{
props.history.push(props.to)
}
const Tag=props.tag||'a'
const Active=props['active-class']||'router-active-class'
return (
<Route path={props.to} children={({match})=>{
if(match){
return <Tag style={{color:'red'}} Onclick={gourl}>{props.children}</Tag>
}
return <Tag onClick={gourl}>{props.children}</Tag>
}}>
)
}
export default withRouter(MyLink)
在有一些功能中,往往请求地址的前缀是相同的,不同的只是后面一部份,此时就可以使用多级路由(路由嵌套)来实现此路由的定义实现。
例: 路由规则如下
admin/index
admin/user
当前组建的请求uri地址(父组件路由uri)
let pathname=this.props.match.path
return(
<Link to=`${pathname}/index`>用户首页</Link>
<Link to=`${pathname}/list`>用户列表</Link>
写在admin组件内,admin组件通过route来进行渲染
<Route path={`${pathname}/index`} component={main}/>
<Route path={`${pathname}/list`} component={index}/>
)
<Redirect from="/home" to="/" />
<Route component={Notfound} />
默认:匹配规则是从上项下的,一只匹配下去
switch组件:解决一直匹配问题,只要有一个符合;路由规则就停止匹配
<Switch>
<Route exact path='/news' component={index}/>
<Route path='/news/:id' component={Newss}/>
重定向from来源,to跳转的页面
<Redirect exact from='/' to='/news'>
<Route component={notFound}>
</Switch>
React Router依赖于history.js
,它是一个独立的第三方js库。可以用来兼容在不同浏览器、不同环境下对历史记录的管理,拥有统一的API。
hash
来存储在不同状态下的history
信息,对应createHashHistory
,通过检测location.hash
的值的变化,使用location.replace
方法来实现url跳转。通过注册监听window
对象上的hashChange
事件来监听路由的变化,实现历史记录的回退。createBrowserHistory
, 使用包括pushState
, replaceState
方法来进行跳转。通过注册监听window
对象上的popstate
事件来监听路由的变化,实现历史记录的回退。createMemoryHistory
。直接在内存里push
和pop
状态。版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.cnblogs.com/ypSharing/p/15587340.html
内容来源于网络,如有侵权,请联系作者删除!