react服务端渲染-nextJs入门圣经

nextJs入门之路由篇

路由跳转

  1. 标签跳转方式

    • 实现方式
    // index.js
    import React from 'react'
    import Link from 'next/link'
    
    const Index = () => {
        return (
            <div>
                <div>index--页面</div>
                <Link href="/about"><a>跳转至about</a></Link>
            </div>
            
        )
    }
    
    export default Index
    
    // about.js
    import Link from 'next/link'
    
    const About =() =>  {
        return (
            <div>
                <button>About</button>
                <Link href="/"><a>返回首页</a></Link>
            </div>
        )
    }
    export default About
    
    • 需要注意的点
      1. link标签里面必须包含a标签
      2. link标签里面不能有兄弟标签
  2. 编程跳转方式

  • 实现
import React from 'react'
import Link from 'next/link'
import Router from 'next/router'
const Index = () => {
    const linkTo = () => {
        // Router.push("/about")
      Router.push({
        pathname: '/about',
        query: {
          name: 'huirong'
        }
      })
    }
    return (
        <div>
            <div>index--页面</div>
            <Link href="/about"><a>跳转至about</a></Link>
            <button onClick={linkTo}>点击跳转至about</button>
        </div>
        
    )
}

export default Index
  1. 路由传参

    nextJs暂时不支持path传递参数

    • query传递参数(home?id=1)

      // index.js
      
      import React from 'react'
      import Link from 'next/link'
      import Router from 'next/router'
      const Index = () => {
          const linkTo = () => {
              Router.push("/about?name=huirong")
          }
          return (
              <div>
                  <div>index--页面</div>
                  <Link href="/about?name='zhugechengying'"><a>跳转至about--zhugechengying</a></Link>
                  <br/>
                  <Link href="/about?name='huirong'"><a>跳转至about--huirong</a></Link>
                  <button onClick={linkTo}>点击跳转至about</button>
              </div>
              
          )
      }
      
      export default Index
      
      // about.js
      import Link from 'next/link'
      import { withRouter } from 'next/router'
      
      const About =({router}) =>  {
          return (
              <div>
                  <button>About</button>
                  <ul>
                      <li>{ router.query.name}, 我可找到你了, 😄</li>
                  </ul>
                  <Link href="/"><a>返回首页</a></Link>
              </div>
          )
      }
      export default withRouter(About)
      
    • 需要注意的点

      1. 需要引入withRouter
      2. 获取参数的时候使用router.query.id
      3. 使用withRouter包裹组件,例如在到处的时候使用withRouter(about)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值