react-router(路由)
程序员文章站
2022-03-26 13:39:53
...
-
我们使用的是4.+版本,使用的是react-router-dom
-
react-router是3.x的版本
-
路由的模式有两种
- 老浏览器提供的 hash模式, 我们称之为: HashRouter
- H5提供的的 hsitory 模式,我们称之为 BrowserRouter
注意: H5模式的路由需要后端支持
-
使用路由
-
书写路由展示区域, 使用 Route
-
重定向
- 第一种
<Route to = "/" component = { Home }/>
- 第二种
- 路径完全匹配 exact
<Route to = "/" component = { Home } exact/>
- Switch
- NavLink
代码:
import React from 'react';
import './App.css';
import { Route,Switch,NavLink } from 'react-router-dom'
import Home from './page/home'
import Mine from './page/mine'
function App() {
return (
<div className="App">
<h3> React-router </h3>
<hr/>
<nav className="nav justify-content-center">
<NavLink activeClassName = "active" className="nav-link" to="/home"> Home </NavLink>
<NavLink activeClassName = "active" className="nav-link" to="/mine"> mine </NavLink>
<NavLink activeClassName = "active" className="nav-link" to="/mine/login"> login </NavLink>
</nav>
<Switch>
<Route path = '/' component = { Home } exact></Route>
<Route path = "/home" component = { Home }></Route>
<Route path = "/mine" component = { Mine } exact></Route>
<Route path = "/mine/login" render = { () => {return <div> login </div>}}></Route>
</Switch>
</div>
);
}
export default App;
外部index.js修改为:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
// 在入口文件 引入react-react-dom
// import { HashRouter as Router } from 'react-router-dom'
import { BrowserRouter as Router } from 'react-router-dom'
ReactDOM.render(
<Router>
<App />
</Router>
, document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();