nextJs入门之路由篇
路由跳转
-
标签跳转方式
- 实现方式
// 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
- 需要注意的点
- link标签里面必须包含a标签
- link标签里面不能有兄弟标签
-
编程跳转方式
- 实现
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
-
路由传参
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)
-
需要注意的点
- 需要引入withRouter
- 获取参数的时候使用router.query.id
- 使用withRouter包裹组件,例如在到处的时候使用withRouter(about)
-