表单组件
<Form> 组件扩展了 HTML <form> 元素,提供了 预取 加载 UI 的功能, 提交时进行客户端导航,以及渐进式增强。
它对于更新 URL 搜索参数的表单非常有用,因为它减少了实现上述功能所需的样板代码。
基本用法
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 - 当
action是一个 function(服务器操作)时,<Form>的行为类似于 React 表单,在表单提交时执行该操作。
action (string) 属性
当 action 是字符串时,<Form> 组件支持以下属性
| 属性 | 示例 | 类型 | 必需 |
|---|---|---|---|
action | action="/search" | string (URL 或相对路径) | 是 |
replace | replace={false} | boolean | - |
scroll | scroll={true} | boolean | - |
prefetch | prefetch={true} | boolean | - |
action:表单提交时要导航到的 URL 或路径。- 空字符串
""将导航到具有更新搜索参数的相同路由。
- 空字符串
replace:替换当前历史状态,而不是向 浏览器历史记录 堆栈推送新状态。默认值为false。scroll:控制导航期间的滚动行为。默认为true,这意味着它将滚动到新路由的顶部,并保持向前和向后导航的滚动位置。prefetch:控制当表单在用户视口中可见时是否预取路径。默认为true。
action (function) 属性
当 action 是函数时,<Form> 组件支持以下属性
| 属性 | 示例 | 类型 | 必需 |
|---|---|---|---|
action | action={myAction} | function (服务器操作) | 是 |
action:表单提交时要调用的服务器操作。有关更多信息,请参阅 React 文档。
须知:当
action是函数时,replace和scroll属性将被忽略。
注意事项
formAction:可在<button>或<input type="submit">字段中使用,以覆盖action属性。Next.js 将执行客户端导航,但是,此方法不支持预取。- 使用
basePath时,您还必须将其包含在formAction路径中。例如:formAction="/base-path/search"。
- 使用
key:不支持将key属性传递给字符串action。如果您想触发重新渲染或执行修改,请考虑改用函数action。
onSubmit:可用于处理表单提交逻辑。但是,调用event.preventDefault()将覆盖<Form>的行为,例如导航到指定的 URL。method、encType、target:不支持,因为它们会覆盖<Form>的行为。- 同样,
formMethod、formEncType和formTarget可分别用于覆盖method、encType和target属性,使用它们将回退到原生浏览器行为。 - 如果需要使用这些属性,请改用 HTML
<form>元素。
- 同样,
<input type="file">:当action是字符串时使用此输入类型,将通过提交文件名而不是文件对象来匹配浏览器行为。
示例
导航到搜索结果页面的搜索表单
您可以通过将路径作为 action 传递来创建一个导航到搜索结果页面的搜索表单
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.js 的 searchParams 属性访问查询,并使用它从外部源获取数据。
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.js 和 loading.js)将被预取。提交时,表单将立即导航到新路由并显示加载 UI,同时获取结果。您可以使用 loading.js 设计回退 UI
export default function Loading() {
return <div>Loading...</div>
}为了应对共享 UI 尚未加载的情况,您可以使用 useFormStatus 向用户显示即时反馈。
首先,创建一个组件,在表单待处理时显示加载状态
'use client'
import { useFormStatus } from 'react-dom'
export default function SearchButton() {
const status = useFormStatus()
return (
<button type="submit">{status.pending ? 'Searching...' : 'Search'}</button>
)
}然后,更新搜索表单页面以使用 SearchButton 组件
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 属性来执行修改。
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。
'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 属性获取数据
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>
)
}有关更多示例,请参阅 服务器操作 文档。
这有帮助吗?