1.下载安装react路由
cnpm i react-router-dom@5 -S
2. 创建1个router.js文件配置路由
import { BrowserRouter , HashRouter , Route , Link , NavLink} from 'react-router-dom'
class App extends Component {
render() {
return (
<BrowserRouter>
<Route path='/' exact component={Home}></Route>
</BrowserRouter>
)
}
} // history模式
class App extends Component {
render() {
return (
<HashRouter>
<Route path='/' exact component={Home}></Route>
</HashRouter>
)
}
} //hash模式
3.路由api说明
Route: 用来控制路径对应显示的组件
path:指定路由跳转路径
exact: 精确匹配路由
component:路由对应的组件
switch:解决route
的唯一渲染,它是为了保证路由只渲染一个路径。没有switch会渲染path上所有的组件
<Switch>
<Route path="/home" component={Home} />
</Switch>
路由跳转组件Link
<Link to={{
pathname: '/home', //路径
search: '?name=cedric', //参数
hash: '#Hash', //放入路径的 hash值
state:{ fromWechat:true }}} //状态持续到 location可用于统计页面来源 this.props.location.state可见
> </Link>
路由跳转组件NavLink可添加高亮效果
<NavLink to="/home" activeStyle={{ fontWeight: 'bold', color: 'red' }} > </NavLink>
路由重定向组件Redirect
<Switch> <Route path='/home' exact component={Home}></Route> <Route path='/login' exact component={Login}></Route> <Redirect to="/home" from='/' exact /> </Switch>
withRouter将一个非路由组件包裹为路由组件,使这个非路由组件也能访问到当前路由的match, location, history对象
编程式导航 - history 对象
this.props.history.push('/home')
写在点击事件里可实现跳转
只有通过 Route 组件渲染的组件,才能在 this.props 上找到 history 对象
路由传参
params 参数
路由链接(携带参数):<Link to='/demo/test/tom/18'}>详情</Link>
注册路由(声明接收):<Route path="/demo/test/:name/:age" component={Test}/>
接收参数:this.props.match.params
search 参数
路由链接(携带参数):<Link to='/demo/test?name=tom&age=18'}>详情</Link>
注册路由(无需声明,正常注册即可):<Route path="/demo/test" component={Test}/>
接收参数:this.props.location.search
state参数
路由链接(携带参数):<Link to={{pathname:'/demo/test',state:{name:'tom',age:18}}}>详情</Link>
注册路由(无需声明,正常注册即可):<Route path="/demo/test" component={Test}/>
接收参数:this.props.location.state