欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

react-router(路由)

程序员文章站 2022-03-26 13:39:53
...
  1. 我们使用的是4.+版本,使用的是react-router-dom

  2. react-router是3.x的版本

  3. 路由的模式有两种

    • 老浏览器提供的 hash模式, 我们称之为: HashRouter
    • H5提供的的 hsitory 模式,我们称之为 BrowserRouter
      注意: H5模式的路由需要后端支持
  4. 使用路由

  5. 书写路由展示区域, 使用 Route

  6. 重定向

  • 第一种
      <Route to = "/" component = { Home }/>
    
  • 第二种
  1. 路径完全匹配 exact
      <Route to = "/" component = { Home } exact/>
    
  2. Switch
  3. 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();