路由的种类
页面路由
12window.location.href = 'http://www.baidu.com';history.back();hash 路由
1234window.location = '#hash';window.onhashchange = function(){console.log('current hash:', window.location.hash);}h5路由
123456789101112// 推进一个状态history.pushState('name', 'title', '/path');// 替换一个状态history.replaceState('name', 'title', '/path');// popstatewindow.onpopstate = function(){console.log(window.location.href);console.log(window.location.pathname);console.log(window.location.hash);console.log(window.location.search);//……}
react-router学习推荐地址:
react-router
<BrowserRouter>,<HashRouter>
,路由方式<Route>
,路由规则<Switch>
,路由选项<Link>,<NavLink>
,跳转导航<Redirect>
,自动跳转
react-router-dom基本使用
- 例: 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768import React from 'react';import ReactDOM from 'react-dom';import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom'class A extends React.Component{constructor(props){super(props)}render(){return (<div>Component A<Switch><Route exact path={`${this.props.match.path}`} render={(route) => {return <div>当前组件是不带参数的A</div>}}/><Route path={`${this.props.match.path}/sub`} render={(route) => {return <div>当前组件是Sub</div>}}/><Route path={`${this.props.match.path}/:id`} render={(route) => {return <div>当前组件是带参数的A, 参数是:{route.match.params.id}</div>}}/></Switch></div>)}}class B extends React.Component{constructor(props){super(props)}render(){return <div>Component B</div>}}class Wrapper extends React.Component{constructor(props){super(props)}render(){return (<div><Link to="/a">组件A</Link><br/><Link to="/a/123">带参数的组件A</Link><br/><Link to="/b">组件B</Link><br/><Link to="/a/sub">/a/sub</Link>{this.props.children}</div>);}}ReactDOM.render(<Router><Wrapper><Route path="/a" component={A}/><Route path="/b" component={B}/></Wrapper></Router>,document.getElementById('app'));