【问题标题】:Next.js + React Go back to the previous pageNext.js + React 返回上一页
【发布时间】:2019-01-21 09:51:55
【问题描述】:

我使用路由 next.js。如何实现按钮返回和返回上一页?就像浏览器上的按钮一样

【问题讨论】:

  • 您可能需要查看Next.js getting started 页面。
  • 查看但没有找到解决方案。我试图这样做,但得到了不断的页面重定向。 export const BackUrl = ({url}) => (  

    Nazad

    )
  • Client-Side History Support 状态:When you hit the Back button, it navigates the page to the index page entirely via the client; 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.。所以你不需要onClick 属性和window.history.back()

标签: reactjs next.js


【解决方案1】:

编辑:在此答案首次发布 2 年后,路由器方法现在为 well documented。这是直接来自文档的代码:

import { useRouter } from 'next/router'

export default function Page() {
  const router = useRouter()

  return <span onClick={() => router.back()}>Click here to go back</span>
}

原始答案:

有一个未记录的 Router.back 方法 (see source) 只执行 window.history.back()

你应该有这样的组件

import Router from 'next/router'

export default function BackButton() {
    return (
        <div onClick={() => Router.back()}>Go Back</div>
    )
}

【讨论】:

  • 值得指出的是,如果您在 CSS 中为 :hover 分配了元素,由于 onClick 在移动设备上的触发方式,您可能会在移动设备上遇到奇怪的行为。
  • 这只是隐藏了完全相同的代码行。 @Clément 的链接来自 next 7,v8 也一样:github.com/zeit/next.js/blob/v8.0.4/packages/next-server/lib/…
  • 嗯...我不认为这很友好...
  • @AnatoleLucet 非常好的一点,如前所述,这是官方的 nextjs 示例。我知道 nextjs 团队喜欢这种反馈,也许告诉他们,他们会更新文档。至于这个答案,我不想偏离官方文档以保持简单
猜你喜欢
  • 1970-01-01
  • 2022-01-13
  • 2021-01-20
  • 1970-01-01
  • 2011-02-02
相关资源
最近更新 更多