React中的路由

版权声明: https://blog.csdn.net/weixin_41849462/article/details/84025814

什么是React路由

  • 主要使用HTML5的history API来同步UI和url
  •   Router相当于一个容器,不会被渲染出来。组件都要放在Router里面使用react-router的功能。
  •   Link被渲染称一个a标签,通常以声明式的方式被定义在应用程序中
  •   Route包含一个path,并指明了在path与URL匹配时要渲染的组件。
  •   ( 如果说我们的应用程序是一座小城的话,那么Route就是一座座带有门牌号的建筑物,而Link就代表了到某个建筑物的路线。有了路线和目的地,那么就缺一位老司机了,没错Router就是这个老司机)

react路由中的(Prompt、Redirect、match、Switch)

1、Prompt组件 
它有一个必须的属性message,用于给用户提示信息。每当用户进行切换时,都会提示一条消息。 
但是,有时候,我们希望提示消息,有时候我们不希望提示出现,这就用到它的另外一个属性-when。when有两种情况,当它的值是true时,会提示消息。当它的值为false时,不会提示消息。 
使用方式:

<Prompt when={true} message="您确定要离开当前页面吗?"/>

2.Redirect组件 

用一个对应的新的地址的Route,来指定重定向的界面

<Route path="/home" render={()=><Redirect to="/other"/>}/>

重定向有两种方式<Redirect> 标签和编程式导航方式

1.<Redirect to={'/default'}/>


2.this.props.history.push('/default')

3.match对象 

match是一个匹配路径参数的对象,它有一个属性params,里面的内容就是路径参数,除常用的params属性外,它还有url、path、isExact属性。

class Match extends Component{
    render(){
        return (
            <div>id:{this.props.match.params.id}</div>
        )
    }
}

class Main extends Component{
    constructor(props){
        super(props);
    }
    render(){
        return (
            <Router>
                <div>
                    <ul>
                        <li><Link to="/home">首页</Link></li>
                        <li><Link to="/other">其他页</Link></li>
                    </ul>

                    <Route path="/:id" component={Match}/>
                </div>
            </Router>
        )
    }
}

4.Switch组件 

它的特性是我们只渲染所匹配到的第一个路由组件,一般界面渲染的时候,会渲染所有匹配到的路由组件。它的孩子节点只能是Route组件或者Redirect组件。

import { Switch } from "react-router-dom";

<Switch>
    <Route path="/" component={Test1} />
    <Route path="/Test" component={Test2} />
</Switch>

react路由怎样进行传参

方式 一

         通过params

        1.路由表中                   

<Route path=' /sort/:id '   component={Sort}></Route> 

      

        2.Link处        

            HTML方式

  <Link to={ ' /sort/ ' + ' 2 ' }  activeClassName='active'>XXXX</Link>       

          JS方式    

 this.props.router.push(  '/sort/'+'2'  )  

        3.sort页面       

               通过  this.props.params.id        就可以接受到传递过来的参数(id)

 方式 二

         通过query

                前提:必须由其他页面跳过来,参数才会被传递过来

        注:不需要配置路由表。路由表中的内容照常:<Route path='/sort' component={Sort}></Route>

        1.Link处      

         HTML方式

           

 <Link to={{ path : ' /sort ' , query : { name : 'sunny' }}}>

       

       JS方式     

    this.props.router.push({ path : '/sort' ,query : { name: ' sunny'} })

        2.sort页面     

      this.props.location.query.name

   方式 三

        通过state

            同query差不多,只是属性不一样,而且state传的参数是加密的,query传的参数是公开的,在地址栏

        1.Link 处      

          HTML方式:

 <Link to={{ path : ' /sort ' , state : { name : 'sunny' }}}> 

         JS方式:

 this.props.router.push({ pathname:'/sort',state:{name : 'sunny' } })

  

        2.sort页面       

 this.props.location.state.name

react路由嵌套

const Topics = ( {match} ) => {
    return  <div>
              <h3>我是列表</h3>
              <ul>
                <li><Link to={`${match.url}/react`}>a</Link></li>
                <li><Link to={`${match.url}/router`}>b</Link></li>
                <li><Link to={`${match.url}/redux`}>c</Link></li>
              </ul>
              <hr/>
              <Route path={`${match.url}/:topicId`} component={Topic}/>
            </div>
};
const Topic = ({match}) => {
  return <div><h3>{match.params.topicId}</h3></div>
};
 
class App extends Component {
  render() {
    return (
        <Router>
           <div>
             <ul>
               <li><Link to="/">首页</Link></li>
               <li><Link to="/about">关于</Link></li>
               <li><Link to="/topics">列表</Link></li>
             </ul>
             <hr/>
             <Route exact={true} path="/" component={Home}  />
             <Route path="/about" component={About} />
             <Route path="/topics" component={Topics} />
           </div>
        </Router>
    );
  }
}
export default App
1.首先在Topics组件上 有个match对象,然后我们继续在Topics组件定义 Link 在路径上 to={`${match.url}/react`}  ` ${match.url}` 返回的就是 '/topics'    所以{`${match.url}/react`}  == '/topics/react'

Link和NavLink

Link

// to为string
<Link to="/about">关于</Link>
 
// to为obj
<Link to={{
  pathname: '/courses',
  search: '?sort=name',
  hash: '#the-hash',
  state: { fromDashboard: true }
}}/>
 
// replace 
<Link to="/courses" replace />
  • 如果使用锚点元素实现,在每次点击时,页面被重新加载,React Router提供了<Link>组件用来避免这种状况发生。当 你点击<Link>时,url会更新,组件会被重新渲染,但是页面不会重新加载
  • <Link>使用to参数来描述需要定位的页面。它的值既可是字符串,也可以是location对象(包含pathname、search、hash、与state属性)如果其值为字符串,将会被转换为location对象
  • replace(bool):为 true 时,点击链接后将使用新地址替换掉访问历史记录里面的原地址;为 false 时,点击链接后将在原有访问历史记录的基础上添加一个新的纪录。默认为 false;
  • Link 组件最终会渲染为 HTML 标签 <a>,它的 to、query、hash 属性会被组合在一起并渲染为 href 属性

NavLink

  • <NavLink>是<Link>的一个特定版本,会在匹配上当前的url的时候给已经渲染的元素添加参数,组件的属性有
  • activeClassName(string):设置选中样式,默认值为active
  • activeStyle(object):当元素被选中时,为此元素添加样式
  • exact(bool):为true时,只有当导致和完全匹配class和style才会应用
  • strict(bool):为true时,在确定为位置是否与当前URL匹配时,将考虑位置pathname后的斜线
  • isActive(func)判断链接是否激活的额外逻辑的功能

猜你喜欢

转载自blog.csdn.net/weixin_41849462/article/details/84025814