我需要在 nextjs 中使用 onkeypress 重定向用戶。
我有一個搜索輸入,用戶可以在其中輸入,然后按 Enter 鍵轉到另一個頁面。
我試過的:
const handler = (e) => {
const ENTER = 13;
if (e.keyCode === ENTER) // do a history.push("/news");
console.log("enter");
};
<input
onKeyPress={(e) => handler(e)}
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"
/>
我會很感激你的幫助。
uj5u.com熱心網友回復:
檔案涵蓋了這一點:
勢在必行
next/link 應該能夠滿足您的大部分路由需求,但您也可以在沒有它的情況下進行客戶端導航,請查看 next/router 的檔案。
以下示例展示了如何使用 useRouter 進行基本頁面導航:
import { useRouter } from 'next/router' export default function ReadMore() { const router = useRouter() return ( <button onClick={() => router.push('/about')}> Click here to read more </button> ) }
uj5u.com熱心網友回復:
您可以使用useRouter下一個鉤子 - https://nextjs.org/docs/api-reference/next/router
嘗試將您的處理程式更改為
import {useRouter} from "next/router";
const Component = () => {
const router = useRouter();
const handler = (e) => {
...
router.push("/news");
}
return (
<input
onKeyPress={handler}
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"
/>
)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/497839.html
標籤:javascript 下一个.js
