react-router-dom5.x的基本使用
安装
npm install --save react-router-dom
使用
导入
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
- 上述import是es6语法,其中as是取别名用的
简单实例
import React from 'react';
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import Home from './components/Home'
import News from './components/News'
import Music from './components/Music'
function App() {
return (
<Router>
<Route exact path="/" component={Home} />
<Route path="/news" component={News} />
<Route path="/music" component={Music} />
</Router>
);
}
export default App;
- 注意,每个路由必须被外层的Router包裹
- exact的存在是严格匹配,去掉的话,访问/news实际会渲染Home,News两个组件
Link的使用
- 类似vue的vue-router,实际每个Link默认被渲染为a标签
<Link to='/' > 首页</Link>
<Link to='/news'>新闻</Link>
<Link to='/music'>音乐</Link>