安装
npm install --save react-router-dom
yarn add react-router-dom -S
基本使用
react-rouer中奉行一切皆组件的思想,路由器Router,链接Link,路由Route,独占Switch,重定向Redirect都以组件形式存在。
BrowserRouter
src/pages/RouterPage.js
import React, { Component } from 'react'
import {BrowserRouter,Link,Route,Switch} from "react-router-dom";
import HomePage from "./HomePage"
import UserPage from "./UserPage"
export default class RouterPage extends Component {
render() {
const id = 123
return (
<div>
<BrowserRouter>
<Link to='/'>首页</Link>
<Link to='/user'>用户中心</Link>
{/* 动态路由 */}
<Link to={'/search/' + id}>搜索</Link>
<Link to='/aaa'>不知道的页面</Link>
{/* 独占路由 从上到下匹配 匹配一个就返回 404写在最后 */}
<Switch>
{/* component children render只会显示一个 优先级最高是children 然后是component */}
{/* exact 准确匹配 严格匹配 */}
<Route exact path="/"
component={HomePage}
children={()=><div>haha</div>}
render={()=><div>1122</div>}
>
</Route>
<Route path="/user" component={UserPage}></Route>
<Route path="/search/:id" component={Search}></Route>
<Route component={()=><div>404</div>}></Route>
</Switch>
</BrowserRouter>
</div>
)
}
}
// 嵌套路由
function Search(props){
console.log(props);
const {id} = props.match.params;
return (
<div>Search:{id}
<Link to="/search/detail">{id}详情</Link>
{/* 子路由写组件里 */}
<Route path="/search/detail" component={Detail}></Route>
</div>
)
}
function Detail(props){
return <div>Detail</div>;
}
src/pages/HomePage.js
import React, { Component } from 'react'
export default class HomePage extends Component {
render() {
return (
<div>
<h1>HomePage</h1>
</div>
)
}
}
src/pages/UserPage.js
import React, { Component } from 'react'
export default class UserPage extends Component {
render() {
return (
<div>
<h1>UserPage</h1>
</div>
)
}
}