文章目录
- 文章参考
- 快速引入路由模块
- 引入react-router-dom依赖包
- 引入BrowserRouter放到最外层根节点
- BrowserRouter 放在根节点的作用
- Router 组件引入路由配置
- react-router-dom模块提供了哪些组件?
- <Link> 组件导航
- 快速页面切换
- 传递参数
- react-router-dom编程式导航
- this.props.history.replace('/detail');
- this.props.history.goBack();
- `子路由Route不能使用exact属性 ?`
- restful动态路由
- 定义动态路由
- 获取路由的参数
文章参考
- React-Router-DOM学习笔记
- 官方文档
快速引入路由模块
引入react-router-dom依赖包
npm install react-router-dom --save-dev
引入BrowserRouter放到最外层根节点
我们需要再项目入口文件index.js引入react-router-dom依赖:
import {BrowserRouter} from "react-router-dom";
ReactDOM.render(
<BrowserRouter>
<Router/>
</BrowserRouter>,
document.getElementById("root")
);
BrowserRouter 放在根节点的作用
- 路由控制的范围,在整个项目中
- BrowserRouter说明是采用history模式,HashRouter 是采用 hash 模式
Router 组件引入路由配置
class Router extends Component{
render(){
return (
<Switch>
<Route exact path="/" component={PageA}/>
<Route path="/pagea" component={PageA}/>
<Route path="/pageb" component={PageB}/>
<Route path="/pagec" component={PageC}/>
<Redirect to='/' />
</Switch>
);
}
}
- Switch: 是从上往下读,只要有一个匹配成功,就不会往下读
- Route:匹配路径,导入组件
a. exact的值为bool型,为true时表示严格匹配,为false时为正常匹配
b. render方法只有在路由匹配时才触发
c. children方法不管路由匹不匹配都会触发 - Redirect 组件(重定向)
react-router-dom模块提供了哪些组件?
BrowserRouter:路由模式采用的是history, HashRouter采用的路由模式是 hash
- Switch: 里面只能使用 Route 和 Redirect 组件,是从上往下读,
只要有一个匹配成功,就不会往下读
- Route: 匹配路径,导入组件
a. exact的值为bool型,为true时表示严格匹配,为false时为正常匹配
b. render方法只有在路由匹配时才触发
c. children方法不管路由匹不匹配都会触发 - Link: 编程式导航,link在内部做了一个操作,把标签变成了a标签
- NavLink: 的特殊版本,当匹配当前URL时,会给当前link添加样式。
a. 例如<NavLink to='/' activeClassName='active'>home</NavLink>
<Link> 组件导航
快速页面切换
<Link to="/today" />
传递参数
- 使用query,地址栏后面传递参数
<Link to='/courses?sort=name' />
- 使用JSON 对象传递参数
<Link to={{
pathname: '/courses',
search: '?sort=name',
hash: '#the-hash',
state: {
fromDashboard: true
}
}} />
react-router-dom编程式导航
- 传递字符串
this.props.history.push('/detail');
- 使用JSON对象切换页面
this.props.history.push({对象})
export default class Home extends React.Component {
constructor(props) {
super(props);
}
jumpPage = () => {
this.props.history.push({
pathname: '/detail',
search: "?sort=name",
hash: "#the-hash",
state: {
id: 3
}
})
}
render() {
return (
<div>
<button onClick={this.jumpPage}>通过函数跳转</button>
</div>
)
}
}
接收参数的方式
*. 使用 this.props.history.location.state
来接收传递过来的参数
*. 地址栏会出现 /detail?sort=name#the-hash
内容
this.props.history.replace(’/detail’);
在可能会出现死循环的地方使用replace来跳转; 跳转到 ‘/detail’ 路径
this.props.history.goBack();
返回上级页面的时候使用
子路由Route不能使用exact属性 ?
- 因为 exact 表示精确匹配
- 子路由的路径必须依赖父组件,因此路径必须包含父组件的路由
- 但是父组件的路由是exact,则父组件就没有办法匹配,则父组件不会渲染,则子组件就没有办法显示内容
restful动态路由
定义动态路由
<Route exact path="/detail/:newsid" component={Detail}/>
获取路由的参数
this.props.match.params.newsid
更多推荐
react-router-dom 路由跳转API
发布评论