1. Introduction of routing

Most modern front-end applications are SPAs (single-page applications), which are applications with only one HTML page. It is more popular because of its better user experience and less strain on the server. In order to effectively use a single page to manage the original multi-page function, front-end routing came into being. Front-end routing functionality: Allows users to navigate from one view (page) to another

  • Front-end routing is a set ofMapping rulesIn React, yesThe URL pathcomponentThe corresponding relation of
  • React Routing is simple: Configure paths and components (pairing)

Two, the basic use of routing

NPM I [email protected] attention!! Import {HashRouter, Route, import {HashRouter, Route, import {HashRouter, Route, import {HashRouter, Route, import} Link} from 'react-router-dom' Use 'Route' to specify routing rules. Import React from 'React' import ReactDom from 'React' import { HashRouter, Route, Link } from 'react-router-dom' import Search from './pages/Search.jsx' import Comment from './pages/Comment.jsx' export Default function App () {return (<div> <h1>react Routes use </h1> <HashRouter> <Link to="/comment"> comment </Link> <Link </Link> <Route path="/comment" component={comment} /> <Route path="/search" component={search} /> </HashRouter> </div>)} reactdom.render (<App />, document.getelementbyId ('root')) 'HashRouter' and 'BrowserRouter' - HashRouter: Implemented using hash values of urls (<http://localhost:3000/#/first>) - Principle: This is done by listening for the Window's 'hashchange' event - (recommended) BrowserRouter: Using the history of H5. PushState () API implementation (< http://localhost:3000/first >) - principle: monitored window ` popstate ` eventsCopy the code

3, Navlink and Link

  1. Link

The Link component is eventually rendered as an A tag, which is used to specify route navigation

  • The to attribute, which will be rendered as the href attribute of the A tag
  • LinkComponent cannot show which link is selected
  1. NavLink

The NavLink component, a more specialized Link component, can be used to specify the current navigation highlighting

Format:

<NavLink to="/ XXX "activeClassName="active">Copy the code

Description:

  • The to attribute, which specifies the address, is rendered as the href attribute of the A tag
  • ActiveClassName: Used to specify the highlighted class name, defaultactive. Generally not to modify.
  • Exact: exact match. It takes effect only when the value of the address bar and to attribute matches the class name exactly

Conclusion:

1 Link and NavLink are used to redirect routes. They all specify jump addresses with attributes

The difference between 2 Link and NavLink is that the path pointed to by NavLink has a class name named Active