You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js中如何通过onKeyPress监听回车键实现页面跳转

核心问题点

你的代码无法生效有3个关键原因:

  • onKeyPress事件已被Web标准废弃,多数现代浏览器对该事件的兼容性较差,容易出现事件不触发的问题
  • 直接调用原生history.push不符合Next.js路由设计逻辑,会丢失客户端路由的预加载、页面状态缓存等特性,在不同Next.js版本中容易出现跳转异常
  • 旧的keyCode属性同样已被标准废弃,判断按键推荐使用更稳定的key属性

正确实现方案

首先将事件替换为兼容性更好的onKeyDown,同时使用Next.js官方提供的路由hook做跳转,根据你使用的路由模式选择对应写法:

1. Pages Router 版本(pages目录下的页面)

import { useRouter } from 'next/router'
import { useCallback } from 'react'

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

  const handleKeyDown = useCallback((e) => {
    if (e.key === 'Enter') {
      e.preventDefault()
      // 获取输入框的搜索内容
      const searchKeyword = e.target.value.trim()
      // 纯跳转/news页就写 router.push('/news'),带参数就拼接查询串
      router.push(`/news?keyword=${encodeURIComponent(searchKeyword)}`)
    }
  }, [router])

  return (
    <input
      onKeyDown={handleKeyDown}
      type="text"
      name="search"
      placeholder="Search by keywords"
      className="p-4 md:p-6 w-full  py-2 md:py-4 border-2 text-lg md:text-2xl xl:text-3xl border-gray-400 outline-none filosofia_italic bg-white placeholder-gray-400"
    />
  )
}

2. App Router 版本(Next.js 13+,app目录下的页面)

'use client' // 客户端组件必须添加该指令
import { useRouter } from 'next/navigation'
import { useCallback } from 'react'

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

  const handleKeyDown = useCallback((e) => {
    if (e.key === 'Enter') {
      e.preventDefault()
      const searchKeyword = e.target.value.trim()
      router.push(`/news?keyword=${encodeURIComponent(searchKeyword)}`)
    }
  }, [router])

  return (
    <input
      onKeyDown={handleKeyDown}
      type="text"
      name="search"
      placeholder="Search by keywords"
      className="p-4 md:p-6 w-full  py-2 md:py-4 border-2 text-lg md:text-2xl xl:text-3xl border-gray-400 outline-none filosofia_italic bg-white placeholder-gray-400"
    />
  )
}

更推荐的语义化写法

如果输入框外层可以套<form>标签,直接监听表单提交事件即可,不需要单独绑定键盘事件,天然支持回车触发,可访问性更好:

const handleSubmit = (e) => {
  e.preventDefault()
  // 通过表单的name属性直接获取输入值
  const searchKeyword = e.target.search.value.trim()
  router.push(`/news?keyword=${encodeURIComponent(searchKeyword)}`)
}

<form onSubmit={handleSubmit}>
  <input
    type="text"
    name="search"
    placeholder="Search by keywords"
    className="p-4 md:p-6 w-full  py-2 md:py-4 border-2 text-lg md:text-2xl xl:text-3xl border-gray-400 outline-none filosofia_italic bg-white placeholder-gray-400"
  />
</form>

注意事项

  • 拼接路由参数时务必用encodeURIComponent转义关键词,避免特殊字符导致路由解析错误
  • 如果需要跳转后清空输入框,在路由跳转逻辑后加e.target.value = ''即可
  • 如果跳转后需要立即滚动到页面顶部,可以在router.push之后加window.scrollTo(0, 0)

内容的提问来源于stack exchange,提问作者Divad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 05:45:07