我有Radio按钮:A、B和C.
在按钮B下,有一个 Select 框,只有在 Select B时,我才想使此 Select 框为"必需".
这是简化的代码:
interface ButtonFormType {
notificationType: "A" | "B" | "C";
selectedId?: string;
}
const {
register,
handleSubmit,
getValues,
watch,
formState: { errors },
} = useForm<ButtonFormType>();
.
.
.
return(
<form onSubmit={submit}>
<RadioGroup defaultValue={getValues("buttonType")}>
<VStack>
<Radio {...register("buttonType")} value={"A"}> Button A </Radio>
<Radio {...register("buttonType")} value={"B"}> Button B </Radio>
<FormControl isInvalid={!!errors[`selectedId`]}>
<Select
placeholder={"select"}
{...register("selectedId", {
required:
getValues("buttonType") === "B"
? "please select id"
: false,
})}
>
{idList.map(({ id, title }) => {
return (
<option key={id} value={id}>
{title}
</option>
);
})}
</Select>
</FormControl>
<Radio {...register("buttonType")} value={"C"}> Button C </Radio>
</VStack>
</RadioGroup>
<HStack marginY="40px" spacing={4}>
<Button type="submit"> Submit </Button>
</HStack>
</form>
)
当我 Select 按钮B(不从 Select 框中 Select 任何内容)并点击提交按钮时, 它不会给我任何错误.
如果我再次点击提交按钮,它会显示错误消息.
我判断了一下,发现getValues("buttonType")
没有在我更改buttonType后立即更新.
一旦我点击提交按钮,它就会更新.为什么?
我可以通过这样将getValues
更改为watch
来解决这个问题
required:
watch("buttonType") === "B"
? "please select id"
: false,
但仍然不明白为什么getValues不起作用. 有人知道吗?