目标
我正在为买家和卖家建立一个双边市场。当某人导航到我的注册页面时,他们可能会点击以下URL之一
-
/signup
-
/signup?accountType=buyer
-
/signup?accountType=seller
-
/signup?accountType=asdfghjkl
(无意义,但可能)
我的注册页面有一个单选按钮输入,在那里他们选择买方或卖方。
规则
- 用户必须选择其中一个选项。
-
如果URL包含
accountType=buyer
,我希望将默认选择设置为“买家” -
如果URL包含
accountType=seller
,我希望将默认选择设置为卖方 - 即使选择了默认选项,用户也应该能够更改它
我尝试过的
我正在努力使用Next.js和react hook表单实现这一功能。这是我尝试过的。
// Fields.jsx import { forwardRef } from 'react' function Label({ id, children }) { return ( <label htmlFor={id}> {children} </label> ) } export const RadioFieldWithRef = forwardRef(function RadioField({ id, label, options, name, className = '', ...props }, ref) { return ( <div className={className}> {label && <Label id={id}>{label}</Label>} <div> {options.map((option) => ( <div className="flex items-center" key={option.value}> <input id={option.value} name={name} type="radio" value={option.value} defaultChecked={option.defaultChecked} ref={ref} {...props} /> <label htmlFor={option.value}> {option.label} </label> </div> ))} </div> </div> ) })
// signup.jsx import { useRouter } from 'next/router' import { RadioFieldWithRef } from '@/components/Fields' import { useForm } from "react-hook-form"; export default function Signup() { const router = useRouter() const { accountType } = router.query // Email & Password Sign Up Form const { register } = useForm(); const accountTypeField = register("account_type", { required: "Must select account type" }) return ( <form> <RadioFieldWithRef label="I'm a ..." name="account_type" options={ [ { label: 'Buyer', value: 'buyer', defaultChecked: accountType === "buyer" }, { label: 'Seller', value: 'seller', defaultChecked: accountType === "seller" }, ] } {...accountTypeField} /> <button type="submit">Submit</button> </form> ) }
问题
当我尝试/signup?accountType=buyer
这样的URL时,未设置默认选择。我认为这是因为router.query
实际上在第一次渲染时未定义console.log("accountType", accountType)
在最终显示buyer
之前显示undefined
。但我不确定如何克服这一点。