温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何理解react路由Link配置

发布时间:2021-11-10 22:40:42 来源:亿速云 阅读:131 作者:柒染 栏目:开发技术

如何理解react路由Link配置,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

1、Link的to属性

(1)放置路由路径
(2)放置对象,且为规定格式
{pathname:"/xx",search:'?键值对',hash:"#xxx",state:{键值对}}
会自动将pathname、search、hash拼接在url路径上,state为传入的参数
可通过输出props查看对象内的信息
this.props.location.state.键名获取state内的数据

2、Link的replace属性

添加replace将跳转前的上一个页面替换成当前页面,只将当前页面入栈

3、Link传参

在to路径后添加"/键值"
在路由route,path路径后添加"/:键名"
在组件中,函数式组件:先传入props形参,然后props.match.params.键名
类组件:this.props.match.params.键名

代码示例:

import React,{Component} from 'react'
//import {Route,BrowserRouter,Link} from 'react-router-dom'
//将BrowserRouter重命名为Router
import {BrowserRouter as Router,Link,Route} from 'react-router-dom'
import { Button } from 'antd';
import './App.css';

function Home()
{
  return(
      <div>admin首页</div>
    )
}

function Me(props)
{
  console.log(props)
  return(
      <div>admin我的</div>
    )
}

function Product(props)
{
  return(
      <div>admin产品页面:{props.match.params.id}</div>
    )
}

export default class App extends Component{
   constructor()
    {
      super();
    }
    render()
    {
    {/*若将路径写成对象形式,且和下面相同,会自动将pathname、search、hash自动拼接在url路径上,state为传入组件的数据*/}
      let obj={pathname:"/me",search:'?username=admin',hash:"#abc",state:{msg:'hello'}}
      return(
        <div id='app'>
      {/*BrowserRouter可以放多个*/}
          <Router>
        
        {/*因为组件也是返回html内容,故可以直接通过函数返回html内容充当组件,但不能直接写html内容*/}
          <div>  
            <Route path="/"  exact component={()=><div>首页</div>}></Route>
            <Route path="/product"  component={()=><div>product</div>}></Route>
            <Route path="/me"  component={()=><div>me</div>}></Route>
          </div>
          {/*<Route path="/" component={function(){return <div>首页2</div>}}></Route>*/}

          </Router>
        

          
          {/*BrowserRouter内部只能有一个根容器,包裹其他内容*/}
        {/*添加basename='/xx'后,点击Link跳转其他路由时,url会将/xx添加到路由名前,所以使用路由路径和加了admin的路由路径都能匹配该路由*/}
          <Router basename='/admin'>
            <div>
                <div className='nav'>
                    <Link to='/'>Home</Link>
                    <Link to='/product/123'>Product</Link>
                  {/*可在对应的组件中输出props查看传入的对象的信息,添加replace将跳转前的上一个页面替换成当前页面,只将当前页面入栈*/}
                    <Link to={obj} replace>个人中心</Link>
                </div>

                <Route path="/" exact component={Home}></Route>
                <Route path="/product/:id"  component={Product}></Route>
                <Route path="/me" exact component={Me}></Route>
            </div>
          </Router>

        </div>
        
      )
    }
}

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI