跳到主要内容

5-路由的使用

Create by fall on 2021-12-19 Recently revised in 2021-12-26

路由传参

传递参数

查询字符串

class Button extends React.Component{
render(){
return(
<button>
<Link to={`/home/message/detail?id=${item.id}&title=${item.title}`} >{item.title}</Link>
</button>
)
}
}

传递 state

<li key={item.id}><Link to={pathname: `/home/message/detail`, state:{id:item.id, title:item.title}}>{item.title}</Link></li>
// 接收数据
const {id,titile} = this.props.location.state

V5 路由的使用

路由跳转

import {Link,NavLink} from "react-router"
let link = <Link activeClassName="nav-active" className="nav" to="/about">
about
</Link>
let nav = <NavLink activeClassName="nav-active" className="nav" to="/home">Home</NavLink>
// activeClassName 处于当前路由时,会自动添加该类
// className 当前组件类名
// to 当前组件对应的路由
// NavLink 会添加 class active

注册路由

import {Route} from 'react-router'
let route = <Route path="/home" component={Home}></Route>
let route2 = <Route path="/about" exact component={About}></Route>
// path 监听的路由
// component 该路由绑定的组件
// exact 是否选择严格匹配
// 如果当前路由对应上了路由组件绑定的路由,则会展示所绑定的组件
  • 模糊匹配
    • 如果组件相等或者是包含子路由,则进行启用
  • 严格匹配
    • 完全相等时,才会进行启用该路由

重定向(Redirect)

用户自己输入路由的时候,如果没有注册,不就什么都没有吗,重定向会指定进行默认的跳转

import {Redirct,Route} from 'react-router'
<Route ....../>
<Route ....../>
<Redirect to="/home"/>
// Redirect 放在所有路由的下面,所有都没有匹配到,会跳转到指定路由

Switch 路由

使用 Switch 组件包裹住的所有路由,当出现多个路由匹配的时候,只会渲染第一个匹配的组件

import {Switch,Route,Redirect} from 'react-router'
const switch = <Switch>
<Route .../>
<Route .../>
<Redirect to="..."/>
</Switch>

路由器

ReactDOM.render(<BrowserRouter>
<App></App>
</BrowserRouter>)
// 一共有两种路由方式
// HashRouter BrowserRouter

实现导航栏也拥有路由属性

import { withRouter } from "react-router-dom"
class Header extends Component{
goBack =()=>{
this.props.history.goBack()
}
go=()=>{
this.props.history.go()
}
render(){
console.log(this.props.history)
return (
<div>
<h1>对路由进行测试</h1>
<button onClick={this.goBack}>后退</button>
<button onClick={this.goForward}>前进</button>
<button onClick={this.go}>跳转到上上个路由</button>
</div>
)
}
}
export default withRouter(Header)