一、路由配置(react-router-dom)
配置路由是一组指令,用来告诉router如何匹配URL以及匹配后如何执行代码。
react-router-dom是基于react-router,加入了浏览器运行环境下的一些功能。
如Link组件,会渲染为a标签;
BrowerRouter和HashRouter组件,前者使用pushState和popState事件构建路由,后者
使用window.location.hash和hashchange事件构建路由。
import React ,{Component} from 'react';
import { HashRouter, Route, Link } from 'react-router-dom';
import VirtualDomC from './components/01-VirtualDomC';
import RouterC from './components/08-react-router';
/*
react-router-dom4.0.0++新变化:
(若控制台报错信息为上图是则可能是写法与版本不匹配;)
1、history的使用
a、4.0.0++
import {
HashRouter,// 若在web端请使用BrowserHistory
Route,Link } from 'react-router-dom';
...
render (
<HashRouter>
<div>
<Route exact component={VirtualDomC} path="/"></Route>
<Route exact component={RouterC} path="/RouterC/:id"></Route>
</div>
</HashRouter>
)
b、<4.0.0
import { Router, hashHistory } from 'react-router';
render(
<Router history={hashHistory}>
<div>
<Route exact component={VirtualDomC} path="/"></Route>
<Route exact component={RouterC} path="/RouterC/:id"></Route>
</div>
</Router>
);
2、路由嵌套
render(
<Router history={hashHistory}>
<div>
<Route exact component={VirtualDomC} path="/">
<Route exact component={VirtualDomChild} path="/VirtualDomChild"></Route>
</Route>
<Route exact component={RouterC} path="/RouterC/:id"></Route>
</div>
</Router>
);
*/
class App extends Component {
constructor () {
}
render () {
return (
<HashRouter>
<div>
{/*
<Route>的exact属性:
使路由匹配更加严格,值为true时为严格匹配;为false时正常匹配;
即:为true时,只会加载默认的组件(VirtualDomC),反之,
所有组件都会加载都页面上。
*/}
<Route exact component={VirtualDomC} path='/'></Route>
<Route exact component={RouterC} path='/RouterC/:id'></Route>
</div>
</HashRouter>
)
}
}
export default App;
二、获取路由参数
1、VirtualDomC组件内容
<Link to="/RouterC/666666">点我跳转</Link>
2、RouterC组件中接收参数
this.props.match.params.id
温馨提示:扫码可以提问、交流。本人有各个行业的小程序前端代码,如有需要也可以扫码留言哦。