react-router
官方文档
学习中…
开始倒腾
下载react-router-dom
这个是基于react-router的页面扩展
RN把dom改成native
先create一个react项目,
然后npm i react-router-dom -S
先来个简单的切换
import { BrowserRouter as Router , Route , Link } from 'react-router-dom';
import React , { Component } from "react";
export default class MyRouter extends Component{
constructor(props){
super(props);
}
render(){
return (
<Router>
<ul>
<li>
<Link to="/">首页</Link>
</li>
<li>
<Link to="/page1">页面一</Link>
</li>
<li>
<Link to="/page2">页面二</Link>
</li>
</ul>
<Route path="/" exact component={Index}></Route>
<Route path="/page1" component={Page1}></Route>
<Route path="/page2" component={Page2}></Route>
</Router>
)}
}
function Index(){
return <span>首页</span>
}
function Page1(){
return <span>页面一</span>
}
function Page2(){
return <span>页面二</span>
}
总结
1.路径是/时要加一个属性exact,不加的话,这个route上的组件会一直显示
404页面
当找不到的时候需要一个404页面
import { BrowserRouter as Router , Route , Link ,Switch } from 'react-router-dom';
/*省略*/
<Switch>
<Route path="/" exact component={Index}></Route>
<Route path="/page1" component={Page1}></Route>
<Route path="/page2" component={Page2}></Route>
<Route component={()=><span>404</span>}></Route>
</Switch>
Switch,择一实现,当前面path条件满足时,就不会继续显示之后满足条件的路由,最后path="*“可加可不加
1.注意的,path=”/"的exact的属性不能少,不然就一直是index页面了
/和/index重定向
import { BrowserRouter as Router ,//路由器
Route ,//路由
Link ,//跳转路由
Switch ,//唯一路由
Redirect//路由重定向
} from 'react-router-dom';
<Switch>
<Route path="/" exact component={Index}></Route>
<Route path="/index">
<Redirect to="/"></Redirect>
</Route>
<Route path="/page1" component={Page1}></Route>
<Route path="/page2" component={Page2}></Route>
<Route component={()=><span>404</span>}></Route>
</Switch>
1.可以写成<Route path="/index" component={()=><Redirect to="/"></Redirect>}></Route>
路由传参
<Route path="/page2/:num" component={Page2}></Route>
function Page2(e){
console.log(e);
return <span>页面二{e.match.params.num}</span>
}