react-router简单使用方法
2024-09-07 06:14:24
react-router版本 v4.x
跟着官网 https://reacttraining.com/react-router/ 上的example学习的
使用
<Router>
<header>
<ul>
<li><Link to='/home'>Home</Link</li>
<li><Link to='/about'>About</Link</li>
<li><Link to='/login'>Login</Link</li>
<li><Link to='/register'>Register</Link</li>
</ul>
</header>
<section>
<Route path='/home' component={Home}/>
<Route path='/about' component={About}/>
<Route path='/login' component={Login}/>
<Route path='/register' component={Register}/>
</section>
<footer>
balabalabala...
</footer>
</Router>
说明:当点击Link的时候,对应到Route里就显示对应的组件,section里的Route是替换的实现,也就是说,当点击/home的时候,页面section部分就只显示Home组件的内容
传值
假如,点击List里的项,要传ID到Detail里,这时候就可以用下面的方法来实现
<Route path='/detail/:id' render={(match) => (<Detail xxId={match.params.id}/>)}/>
Detail.jsx
class Detail extends React.Component 大专栏 react-router简单使用方法 class="p">{
render() {
console.log(this.props.xxId); //可以输出List里点击传过来的值
return (<div></div>)
}
}
在V4里只能通过路由地址传值了,想传更多的值,可以借用localStorage来传
非Link跳转
import {withRouter} from 'react-router-dom';
class ComponentA extends React.Component {
//...
_clickHandler() {
this.props.history.push('/login');
}
}
export default withRouter(ComponentA);
路由返回
<div onClick={()=>this.props.history.goBack()}>返回</div>
v2,v3里的跳转,返回和传值
跟v4里有些不同,下面是v2,v3里的写法
import {withRouter} from 'react-router';
class ComponentA extends React.Component {
//...
_clickHandler() {
this.context.router.push('/login')
}
_goBackHandler() {
this.context.router.goBack();
}
}
ComponentA.contextTypes = {
router: PropTypes.object.isRequired
};
export default withRouter(ComponentA);
从路由中取值:
//路由定义
<Route path='/article/:id' component={Detail}/>
//在Detail组件里取值
const {id} = this.props.params;
问题
当从List点击去到Detail里之后,再点击浏览器的返回按钮,List组件的状态就没有了,还不知道是什么原因
补充:这个问题可以通过React-Router(v2,v3)+React-Router-Scroll来解决,详见博客:https://tomoya92.github.io/2017/09/06/reactjs-router-scroll/
原文链接: https://chenyongze.github.io/2017/03/08/react-router-demo/
最新文章
- SQL Server 修改表结构后无法保存的老问题
- Oracle基础函数
- Spotlight on MySQL监控MySQL服务器
- 给定一个函数rand()能产生0到n-1之间的等概率随机数,问如何产生0到m-1之间等概率的随机数?
- @Html.Partial,@Html.Action,@Html.RenderPartial,@Html.RenderAction区别 .(转)
- How to add route for IPV6 interface
- Python闭包与函数对象
- ajax应用篇
- 自制PHP高防防盗链(不是一般的高)(思路)
- [POI2007]ATR-Tourist Attractions [TPLY]
- Flutter中使用sqlite
- mysql严格模式的开启、关闭
- jquery 循环绑定click的问题
- Practise 5.2测试与封装(黑白盒
- eclipse/intellij idea 查看java源码和注释
- SHELL AWK 循环求和
- PS辅助工具Assistor PS
- 521. Longest Uncommon Subsequence I
- java利用poi读取excel异常问题
- Cannot set HTTP gem source: “source https://rubygems.org not present in cache”
热门文章
- restful的简单使用
- JS 判断移动端与PC端
- FullPage.js中文帮助文档API
- jedis异常Broken pipe (Write failed)
- Unable to cast object of type &#39;System.String&#39; to type &#39;System.Int32&#39;.
- 第04项目:淘淘商城(SpringMVC+Spring+Mybatis)【第十天】(单点登录系统实现)
- random mating
- SoapUI+excel接口自动化测试简述
- Uncaught (in promise) NavigationDuplicated {_name: ";NavigationDuplicated";}的解决方法
- 在Orcl中通过SQL语句修改创建表