React路由

3.React路由

npm i react-router-dom

0.路由器

BrowserRouter 和 HashRouter
需在整个APP外层包裹一个路由器才能正常使用注册路由

import {BrowserRouter, HashRouter} from "react-router-dom";

ReactDOM.render(
    <BrowserRouter>
        <App />
    </BrowserRouter>
    ,
    document.getElementById('root')
);

1.基本使用

import {Link, Route} from "react-router-dom";

{/*原生React中,靠路由链接实现切换组件---编写路由链接*/}
<Link className="list-group-item" to='/about'>About</Link>

{/*  注册路由 绑定组件  */}
<Route path='/about' component={About}/>

2.NavLink的使用

import {Route, NavLink} from "react-router-dom";
<NavLink activeClassName='navbar' className="list-group-item" to='/about'>About</NavLink>
{/*  注册路由 绑定组件  */}
<Route path='/about' component={About}/>

3.NavLink封装
之后直接使用MyNavLink即可

import React, {Component} from 'react';
import {NavLink} from "react-router-dom";

class MyNavLink extends Component {
    render() {
        console.log(this.props)
        const {title} = this.props
        return (
            <div>
                <NavLink activeClassName='navbar' className="list-group-item" {...this.props}/>
            </div>
        );
    }
}

export default MyNavLink;

4.Switch的使用

import {Route, Switch} from "react-router-dom";
{/*  Switch标签保证匹配到路由就不再往下匹配,只显示最前面的那个  */}
<Switch>
    <Route path='/about' component={About}/>
    <Route path='/home' component={Home}/>
    <Route path='/home' component={Test}/>
</Switch>

5.解决样式丢失问题

在index.html里引入外部样式时容易引起

<!--    <link rel="stylesheet" href="./css/bootstrap.css" />-->
<!--   解决样式丢失问题, 把前面的点去掉 -->
    <link rel="stylesheet" href="/css/bootstrap.css" />
<!--   或者前面加 %PUBLIC_URL% -->
<!--    <link rel="stylesheet" href="%PUBLIC_URL%/css/bootstrap.css" />-->

6.精准匹配

<MyNavLink to='/about'>About</MyNavLink>
<MyNavLink to='/home/a/b'>Home</MyNavLink>

<Switch>
    {/* exact 开启严格匹配 路径与路由一致 */}
    <Route exact={true} path='/about' component={About}/>
    <Route exact path='/home' component={Home}/>
</Switch>

无法匹配到链接为/home/a/b的路由

7.Redirect使用

import {Route, Switch, Redirect} from "react-router-dom";

<Switch>
    {/* exact 开启严格匹配 路径与路由一致 */}
    <Route path='/about' component={About}/>
    <Route path='/home' component={Home}/>
     {/* 匹配不到默认跳到/about */}
    <Redirect to='/about' />
</Switch>
posted @ 2021-09-03 16:39  tomjoy  阅读(446)  评论(0编辑  收藏  举报