React学习小结(一)

一、index.js的书写步骤:
  
//引入react核心库
import React from ‘react’
//引入ReactDOM
import ReactDOM from ‘react-dom’
// 引入路由
import {BrowserRouter} from 'react-router-dom'
//引入App组件
import App from ‘./App’
//渲染App到页面
ReactDOM.render(
  <BrowserRouter>
    <App/>
  </BrowserRouter>,
  document.getElementById('root')
);  
二、实现样式模块化的方式:
  文件名修改为xxx.module.css
  使用方式:
    // 引入
     import xxx from ‘./xxx.module.css’
    //使用
     className={xxx.类名}
三、 React 路由:
  路由分三种:web、native、anywhere。
  web端使用的路由是react-router-dom

四、关于路由组件的一般组件区别

  1、写法不同:
      一般组件:<DEMO/>
      路由组件:<Route path="/demo" component={DEMO}/>
  2、存放位置不同:
      一般组件:components
      路由组件:pages
  3、接收到的props不同:
      一般组件:写组件标签时传递了什么,就能收到什么
      路由组件:接收到三个固定的属性:history、location、match

五、实现路由链接高亮:

  可以通过NavLink可以实现,通过activeClassName指定样式名,默认高亮的样式名为‘active’

标签体内容也是一个特殊的标签属性,可以通过this.props.children可以获取标签体内容
六、关于Switch和Redirect的使用:
  通常情况下,path和component是一一对应的关系,使用switch可以提高路由匹配效率(单一匹配)。
  Redirect的使用:一般写在所有路由注册的最下方,当所有路由都无法匹配时,跳转到Redirect指定的路由。
<Switch>
    <Route path='/about' component={About}>
    <Route path='/home' component={About}>
    <Redirect to='/home' />
</Switch>

七、路由传参方式:

  分为三种:params传参、search传参、state传参。

  params传参:

路由传参:
<Link to=`message/detail/${id}&&${title}`>
声明接收:
<Route path='/message/detail/:id/:title' component={componentName}/>

组件中获取:
从this.props.match.params中可以直接获取得到  

  search传参:

路由传参:
<Link to=`message/detail?id=${id}&title=${title}`>
声明接收:
<Route path='/message/detail' component={componentName}/>

组件中获取参数:
从this.props.location.search中可以获取到,获取到的是字符串,需要格式化为对象(通过queryString库或者自己写个公共的处理方法)

  state传参:

路由传参:
<Link to={pathname: 'message/detail',state:{id: 11, title:'title'} }>
声明接收:
<Route path='/message/detail' component={componentName}/>

组件中获取参数:
从this.props.location.state中可以获取到,获取到的是对象,可以直接解构使用。

  

posted @ 2021-05-19 16:52  闯入码途的水产人  阅读(45)  评论(0编辑  收藏  举报