React学习第六天

150 阅读1分钟

1.路由的基本使用

  1. 明确界面中的导航区,展示区

  2. 导航去的a标签为Link标签

     <Link to="/hello">hello</Link>
    
  3. 展示区写Route标签进行路径的匹配

    <Route path="/hello" component={Hello}></Route>
    
  4. <App> 的最外层包裹了一个BrowserRouterHashRouter

2.路由组件和一般组件

  1. 写法不同:

    一般组件:<Demo/>

    路由组件:<Route path="/hello" component={Hello}></Route>

  2. 存放位置不同

    一般组件:components

    路由组件:pages

  3. 接收到的props不同

    一般组件:写标签的时候传递什么,接收到的就是什么

    路由组件:接收到三个固定参数 history location match

![image-20211028222414357](/Users/liulu/Library/Application Support/typora-user-images/image-20211028222414357.png)

history

go: *ƒ go(n)*
goBack: *ƒ goBack()*
goForward: *ƒ goForward()*
push: *ƒ push(path, state)*
replace: *ƒ replace(path, state)*

location:

pathname: "/hello"
search: ""
state: undefined

match:

params: {}
path: "/hello"
url: "/hello"

3.NavLink与封装NavLink

  1. NavLink可以实现路由链接的高亮,通过activeClassName指定样式名

  2. 标签体内容是一个特殊的标签属性,可以通过this.props.children拿到标签体内容

image.png

  1. 通过this.props.children可以获取标签体内容
<div>
        {/* 标签体内容 直接在this.props里面拿children */}
      <NavLink {...this.props}/>
</div>

4.Switch的使用

 <Switch>
          <Route path="/hello" component={Hello}></Route>
          <Route path="/welcome" component={Welocome}></Route>
</Switch>
  1. 通常情况下,path 和component是一一对应关系
  2. Switch可以提高路由匹配效率(单一匹配)

5.解决多级路径刷新页面样式丢失问题

  1. public/index.html中引入样式时不写.// (常用)
  2. public/index.html中引入样式时不写./%PUBLIC_URL% (常用)
  3. 使用HahsRouter