react要使用路由需要使用到这个包react-reouter-dom
使用教程
下面是在create-react-app 项目下
1.安装
1
| yarn add react-router-dom
|
2.使用
app.js
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
| import React, {Component} from 'react' import {HashRouter as Router, Route, Link, Switch} from 'react-router-dom'
const Home = () => ( <div> <h2>首页</h2> </div> ) const About = () => ( <div> <h2>关于</h2> </div> )
class App extends Component { render() { return ( <Router> <div> <ul> <li> <Link to="/">首页</Link> </li> <li> <Link to="/about">关于</Link> </li> </ul>
<Switch> <Route exact path="/" component={Home} /> <Route path="/about" component={About} /> </Switch> </div> </Router> ) } }
export default App
|
就可以了
react-router 和 react-router-dom 区别
react-router-dom依赖react-router,所以我们使用npm安装依赖的时候,只需要安装相应环境下的库即可,不用再显式安装react-router。
react-router-dom中package.json依赖:
1 2 3 4 5 6 7 8 9
| "dependencies": { "history": "^4.7.2", "invariant": "^2.2.2", "loose-envify": "^1.3.1", "prop-types": "^15.5.4", "react-router": "^4.2.0", "warning": "^3.0.0" }
|
安装了react-router-dom,npm会解析并安装上述依赖包。可以看到,其中包括react-router。
参考链接:https://github.com/mrdulin/blog/issues/42