Next.js + React Go back to the previous page

前端 未结 2 1589
春和景丽
春和景丽 2021-02-12 15:18

I use routing next.js. How to implement the button back and return to the previous page? Just like with the button on the browser

相关标签:
2条回答
  • 2021-02-12 16:09

    next/link does all the location.history handling for you. You don't need to write even a single line of client-side routing code. This does not take any attribute. Instead create a functional component

    const BsNavLink=(props)=>{
       const {route,title}=props
       return ( <Link  href={route}><a >{title}</a></Link>)
    }
    

    In this case, the child of the next/link component is the anchor tag. It can also work with any other component or tag, the only requirement for components placed inside <Link/> is that they should accept an onClick prop.

    0 讨论(0)
  • 2021-02-12 16:12

    EDIT: 2 years after this answer was first posted, the router method is now well documented. Here is the code straight from the documentation:

    import { useRouter } from 'next/router'
    
    export default function Page() {
      const router = useRouter()
    
      return <span onClick={() => router.back()}>Click here to go back</span>
    }
    

    ORIGINAL ANSWER:

    There is an undocumented Router.back method (see source) that just does window.history.back()

    You should have a component like so

    import Router from 'next/router'
    
    export default function BackButton() {
        return (
            <div onClick={() => Router.back()}>Go Back</div>
        )
    }
    
    0 讨论(0)
提交回复
热议问题