基本上,我有一个表单输入,将用于创建查询参数,一旦将其附加到 URL,查询参数将用于过滤我们拥有的任何服务上的数据。
**
该项目使用应用程序路由系统、Tailwind、react-hook-form 以及 Radix UI。**
我尝试了一些方法,但没有一个起作用。我希望你能帮助我。
'use client'
import { MagnifyingGlassIcon } from '@heroicons/react/24/solid'
import * as Form from '@radix-ui/react-form'
import { Flex } from '@radix-ui/themes'
import { useRouter } from 'next/navigation'
import { useEffect, useMemo, useState } from 'react'
import { Controller, Resolver, useForm } from 'react-hook-form'
type FormValues = {
search: string
}
const resolver: Resolver<FormValues> = async (values) => {
return {
values: values.search ? values : {},
errors: values.search
? {}
: {
search: {
type: 'required',
message: 'This is required.',
},
},
}
}
export const Search: React.FC = () => {
const resolverMemo = useMemo(() => resolver, [])
const [isClient, setIsClient] = useState(false)
const router = useRouter()
useEffect(() => {
setIsClient(true)
}, [])
const {
register,
handleSubmit,
control,
formState: { errors },
} = useForm<FormValues>({ resolver: resolverMemo })
const handleSearch = () => {
handleSubmit((data) => {
if (!data) return
router.push(data.search)
})
}
if (!isClient) {
return null
}
return (
<Form.Root>
<Form.Field name="search">
<Flex width="100%">
<MagnifyingGlassIcon className="h-8 p-2 text-white bg-zinc-800 rounded-l-sm duration-100 hover:scale-105" />
<Form.Control asChild>
<Controller
control={control}
name="search"
render={({ field: { onChange } }) => (
<input
placeholder="Search a project..."
type="search"
className="outline-none border-b border-gray-200 px-4 text-sm focus-within:ring-1 focus-within:ring-blue-400 hover:ring-1 hover:ring-blue-600 focus-within:shadow-md focus-within:shadow-slate-300 rounded-r-lg "
onChange={onChange}
/>
)}
/>
</Form.Control>
</Flex>
</Form.Field>
</Form.Root>
)
}
我的目标是在不渲染的情况下在该输入字段上书写时将查询附加到 URL 参数。
您必须使用 router.replace() 方法而不是 .push 方法,这将阻止添加新的 url 条目。
router.push(data.search)