跳到内容
API 参考组件表单组件

表单组件

<Form> 组件扩展了 HTML <form> 元素,提供了 预取 加载 UI 的功能, 提交时进行客户端导航,以及渐进式增强

它对于更新 URL 搜索参数的表单非常有用,因为它减少了实现上述功能所需的样板代码。

基本用法

/app/ui/search.tsx
import Form from 'next/form'
 
export default function Page() {
  return (
    <Form action="/search">
      {/* On submission, the input value will be appended to
          the URL, e.g. /search?query=abc */}
      <input name="query" />
      <button type="submit">Submit</button>
    </Form>
  )
}

参考

<Form> 组件的行为取决于 action 属性传入的是 string 还是 function

  • action 是一个 string 时,<Form> 的行为类似于使用 GET 方法的原生 HTML 表单。表单数据作为搜索参数编码到 URL 中,当表单提交时,它会导航到指定的 URL。此外,Next.js
    • 预取 在表单可见时预取路径,这会预加载共享 UI(例如 layout.jsloading.js),从而实现更快的导航。
    • 在表单提交时执行 客户端导航 而不是完全页面重新加载。这会保留共享 UI 和客户端状态。
  • action 是一个 function(服务器操作)时,<Form> 的行为类似于 React 表单,在表单提交时执行该操作。

action (string) 属性

action 是字符串时,<Form> 组件支持以下属性

属性示例类型必需
actionaction="/search"string (URL 或相对路径)
replacereplace={false}boolean-
scrollscroll={true}boolean-
prefetchprefetch={true}boolean-
  • action:表单提交时要导航到的 URL 或路径。
    • 空字符串 "" 将导航到具有更新搜索参数的相同路由。
  • replace:替换当前历史状态,而不是向 浏览器历史记录 堆栈推送新状态。默认值为 false
  • scroll:控制导航期间的滚动行为。默认为 true,这意味着它将滚动到新路由的顶部,并保持向前和向后导航的滚动位置。
  • prefetch:控制当表单在用户视口中可见时是否预取路径。默认为 true

action (function) 属性

action 是函数时,<Form> 组件支持以下属性

属性示例类型必需
actionaction={myAction}function (服务器操作)
  • action:表单提交时要调用的服务器操作。有关更多信息,请参阅 React 文档

须知:当 action 是函数时,replacescroll 属性将被忽略。

注意事项

  • formAction:可在 <button><input type="submit"> 字段中使用,以覆盖 action 属性。Next.js 将执行客户端导航,但是,此方法不支持预取。
    • 使用 basePath 时,您还必须将其包含在 formAction 路径中。例如:formAction="/base-path/search"
  • key:不支持将 key 属性传递给字符串 action。如果您想触发重新渲染或执行修改,请考虑改用函数 action
  • onSubmit:可用于处理表单提交逻辑。但是,调用 event.preventDefault() 将覆盖 <Form> 的行为,例如导航到指定的 URL。
  • methodencTypetarget:不支持,因为它们会覆盖 <Form> 的行为。
    • 同样,formMethodformEncTypeformTarget 可分别用于覆盖 methodencTypetarget 属性,使用它们将回退到原生浏览器行为。
    • 如果需要使用这些属性,请改用 HTML <form> 元素。
  • <input type="file">:当 action 是字符串时使用此输入类型,将通过提交文件名而不是文件对象来匹配浏览器行为。

示例

导航到搜索结果页面的搜索表单

您可以通过将路径作为 action 传递来创建一个导航到搜索结果页面的搜索表单

/app/page.tsx
import Form from 'next/form'
 
export default function Page() {
  return (
    <Form action="/search">
      <input name="query" />
      <button type="submit">Submit</button>
    </Form>
  )
}

当用户更新查询输入字段并提交表单时,表单数据将作为搜索参数编码到 URL 中,例如 /search?query=abc

须知:如果您将空字符串 "" 传递给 action,表单将导航到具有更新搜索参数的相同路由。

在结果页面上,您可以使用 page.jssearchParams 属性访问查询,并使用它从外部源获取数据。

/app/search/page.tsx
import { getSearchResults } from '@/lib/search'
 
export default async function SearchPage({
  searchParams,
}: {
  searchParams: Promise<{ [key: string]: string | string[] | undefined }>
}) {
  const results = await getSearchResults((await searchParams).query)
 
  return <div>...</div>
}

<Form> 在用户视口中可见时,/search 页面上的共享 UI(例如 layout.jsloading.js)将被预取。提交时,表单将立即导航到新路由并显示加载 UI,同时获取结果。您可以使用 loading.js 设计回退 UI

/app/search/loading.tsx
export default function Loading() {
  return <div>Loading...</div>
}

为了应对共享 UI 尚未加载的情况,您可以使用 useFormStatus 向用户显示即时反馈。

首先,创建一个组件,在表单待处理时显示加载状态

/app/ui/search-button.tsx
'use client'
import { useFormStatus } from 'react-dom'
 
export default function SearchButton() {
  const status = useFormStatus()
  return (
    <button type="submit">{status.pending ? 'Searching...' : 'Search'}</button>
  )
}

然后,更新搜索表单页面以使用 SearchButton 组件

/app/page.tsx
import Form from 'next/form'
import { SearchButton } from '@/ui/search-button'
 
export default function Page() {
  return (
    <Form action="/search">
      <input name="query" />
      <SearchButton />
    </Form>
  )
}

使用服务器操作进行修改

您可以通过将函数传递给 action 属性来执行修改。

/app/posts/create/page.tsx
import Form from 'next/form'
import { createPost } from '@/posts/actions'
 
export default function Page() {
  return (
    <Form action={createPost}>
      <input name="title" />
      {/* ... */}
      <button type="submit">Create Post</button>
    </Form>
  )
}

修改后,通常会重定向到新资源。您可以使用 next/navigation 中的 redirect 函数导航到新帖子页面。

须知:由于表单提交的“目标”在执行操作之前是未知的,因此 <Form> 无法自动预取共享 UI。

/app/posts/actions.ts
'use server'
import { redirect } from 'next/navigation'
 
export async function createPost(formData: FormData) {
  // Create a new post
  // ...
 
  // Redirect to the new post
  redirect(`/posts/${data.id}`)
}

然后,在新页面中,您可以使用 params 属性获取数据

/app/posts/[id]/page.tsx
import { getPost } from '@/posts/data'
 
export default async function PostPage({
  params,
}: {
  params: Promise<{ id: string }>
}) {
  const { id } = await params
  const data = await getPost(id)
 
  return (
    <div>
      <h1>{data.title}</h1>
      {/* ... */}
    </div>
  )
}

有关更多示例,请参阅 服务器操作 文档。