ReactRouter中提供了以下三大组件:
路由组件:BrowserRouter(history模式) 和 HashRouter (hash模式) 路由匹配组件:Route和Switch 导航组件:Link和NavLink 当然每个组件下又会有几种不同的子类组件实现。比如: Router组件就针对不同功能和平台对应用:
1 2 3 4 5 <BrowserRouter> 浏览器的路由组件 <HashRouter> URL格式为Hash路由组件 <MemoryRouter> 内存路由组件 <NativeRouter> Native的路由组件 <StaticRouter> 地址不改变的静态路由组件
注:路由自动跳转,<Redirect>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 import React,{Component} from 'react'; import ReactDOM from 'react-dom' import { // HashRouter as Router, BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom' class A extends React.Component{ constructor(props){ super(props) } render(){ return ( <div> Component A <br/> {/* 参数是:{this.props.match.params.id} */} <Switch> <Route exact path={`${this.props.match.path}`} render={(route)=>{ return <div>当前组件是不带参数的A组件</div> }} /> <Route exact 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 Component{ constructor(props){ super(props) } render(){ return <div>Component B</div> } } class Wrapper extends Component{ constructor(props){ super(props) } render(){ return ( <div> <Link to="/a">组件A</Link> <br/> <Link to="/a/123">带参数组件A</Link> <br/> <Link to="/a/sub">Sub</Link> <br/> <Link to="/b">组件B</Link> {this.props.children} </div> ) } } ReactDOM.render( <Router> <Wrapper> <Route path="/a" component={A}/> <Route path="/b" component={B}/> </Wrapper> </Router>, document.getElementById('app') )
任何值得做的事就值得把它做好。- Whatever is worth doing is worth doing well.